Python Class inside Class using same methods

2019-08-29 10:25发布

问题:

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 calculate(self):
      variable = 5
      return variable

Do I have to declare this method in both classes, or can I only declare it in the Master, and then use it in Child?

回答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:

class SharedMethods:
    def calculate(self):  
        variable = 5
        return variable

class Master(SharedMethods):
    pass

class Child(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.