Skip to content Skip to sidebar Skip to footer

Python Class Inside Class Using Same Methods

If I writing a class inside a class, and them both use same methods i.e.: class Master: def calculate(self): variable = 5 return variable class Child: def cal

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):
    pass

Here 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"