Please see the following example code, which is in a file, say
classattr.py
class BaseClass(object):
def __init__(self, param1, param2):
self.param1 = param1
self.param2 = param2
def somemethod(self):
return "This is returned when I do Base.__dict__"
class ChildOfBaseClass(BaseClass):
def __init__(self, param1, param2, param3, param4):
super(ChildOfBaseClass, self).__init__(param1, param2)
self.param3 = param3
self.param4 = param4
def somemethod(self, param3, param4):
a = param3 + param4
return a
I want to get all the attributes (I am assuming that param1, param2 etc. are called attributes) of the classes before I create any instance. Command dir(classattr.BaseClass) does not list param1 and param2. It, however, does return the method somemethod.
I am trying to get the attributes for the following reason: The module classattr is imported in another file where the name of the class, either classattr.BaseClass or classattr.ChildOfBaseClass is provided as an input to some function. I want to determine which one it is during the runtime and then use appropriate inputs (either param1 and param2 if the former, or all the parameters param1 to param4 if the latter) when creating the instance. The way I was thinking of doing this is to check whether the class has param3 as an attribute and then creating the instance with correct inputs. Is there another better way to check? Another way is to have param3 and param4 as inputs in BaseClass even if they do not do anything and then always create instance with all four parameters as inputs. But that does not seems appropriate way of doing things.
Thank you.
You can’t know what instance attributes a class will give to its instances, because they don’t exist before an instance is created.
However, if what you want is to know what parameters you need to pass when instantiating the class, you can inspect the call signature of the class’s
__init__method to see what parameters it accepts. See Determining the number of parameters in a lambda for some information about getting the call signature.Note that there’s no inherent relationship between instance attributes and
__init__parameters. You could have a class like this:. . . which defines an instance attribute without receiving any parameters. (Or vice versa, a class that accepts parameters but doesn’t use them to create instance attributes.)