I wrote the following code trying to figure out how to instantiate the subclasses within the main class.. I came up with something that doesn’t feel right.. at least for me.
Is there something wrong with this type of instancing? Is there a better way to call subclasses?
class Family():
def __init__(self):
self.Father = self.Father(self)
self.Mother = self.Mother(self)
class Father():
def __init__(self, instance = ''):
self = instance if instance != '' else self
print self
def method(self):
print "Father Method"
def fatherMethod(self):
print "Father Method"
class Mother():
def __init__(self, instance = ''):
self = instance if instance != '' else self
print self
def method(self):
print "Mother Method"
def motherMethod(self):
print "Mother Method"
if __name__ == "__main__":
Family = Family()
Family.Father.method()
Family.Mother.method()
What you’ve defined there are not (in Python terminology at least) subclasses – they’re inner classes, or nested classes. I’m guessing that this isn’t actually what you were trying to achieve, but I’m not sure what you did actually want – but here are my four best guesses:
A subclass is where the class inheriting from another class is called a subclass. To make
fathera subclass offamily, use the syntaxclass Father(Family):. What you’ve created here is actually called an Inner Class, not a subclass.When you see something like
Family.Father.method(), it often means Family is a module and Father is a class in that module. In Python,modulebasically means.py file. A module doesn’t have an__init__method, but all code at the top level of the module (such as theif __name__ ...line) gets executed when a module is imported.Similarly, you could make Family a package – which in Python basically means a directory on the filesystem containing an
__init__.pyfile.FatherandMotherwould then be modules or classes within the packagePossibly what you’re trying to achieve is declare that an object of type
Familyalways has aFatherobject and aMotherobject. This doesn’t require nested classes (in fact, nested classes are a completely bizarre way to do this). Just use: