I have a class A
that is inherited by classes A0,A1…An,
some of which are inherited by classes A0a, A0b, A0c, A1a, A2a,…
class A():
def __init__(self,att_1=12,att_2="Blue",att3=False,att4=None)
class A0_end(A):
def __init__(self)
super().__init__(self,att_1=13)
class A1(A):
def __init__(self,att_1=0,att_2="Red",att_X1="hello")
self.att_X1=att_X1
super().__init__(self,att_1=att_1,att_2=att_2)
class A1a_end(A1):
def __init__(self)
super().__init__(self,att_1=att_1,att_2=att_2, att_X1="world")
I would like in the end classes to forbid the use of argument so there is only one way to instantiate the class.
In the above example, all the class prefixed with ‘_end’ respect this rule.
For this, I think I need to know the number of possible argument of __init__()
I could make something in the class A
class A():
def __init__(self,att_1=12,att_2="Blue",att3=False,att4=None)
if '_end' in __class__.__name__:
if self.get_magic_number_of_init_attribute() != 0:
print("error, this is not allowed")
os._exit(1)
I would try not use kwargs if possible (and not change the __init__() arguments if possible).
>Solution :
You can get the function signature of the current scope using the inspect module, which provides several useful functions to get information about live objects.
import inspect
def get_current_function_signature_parameter_num():
# Get the current frame
current_frame = inspect.currentframe()
# Get the outer frame, which is the caller's frame
outer_frame = current_frame.f_back
# Get the function name from the outer frame
function_name = outer_frame.f_code.co_name
# Get the locals from the outer frame
outer_locals = outer_frame.f_locals
# Determine if the function is a method of a class
if 'self' in outer_locals:
# It's a method of a class
cls = outer_locals['self'].__class__
function = cls.__dict__[function_name]
else:
# It's a standalone function
function = outer_frame.f_globals[function_name]
# Get the signature of the function
signature = inspect.signature(function)
# Get the number of parameters
parameter_num = len(signature.parameters)
return parameter_num
Replace self.get_magic_number_of_init_attribute() with get_current_function_signature_parameter_num()-1 should work. Note that self is included as a parameter in class method.