Python Class Inside Class Using Same Methods
Solution 1:
Nesting one class inside another has no other effect than that the nested class becomes an attribute on the outer class. They have no other relationship.
In other words, Child is a class that can be addressed as Master.Child instead of just plain Child. Instances of Master can address self.Child, which is a reference to the same class. And that's where the relationship ends.
If you wanted to share methods between two classes, use inheritance:
classSharedMethods:
    defcalculate(self):  
        variable = 5return variable
classMaster(SharedMethods):
    passclassChild(SharedMethods):
    passHere both Master and Child now have a calculate method.
Since Python supports multiple inheritance, creating a mixin class like this to share methods is relatively painless and doesn't preclude using other classes to denote is-a relationships.
Leave containment relationships to instances; give your Master a child attribute and set that to a Child instance.
Post a Comment for "Python Class Inside Class Using Same Methods"