Python Class inside Class using same methods

旧时模样 提交于 2020-01-06 07:17:10

问题


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.



来源:https://stackoverflow.com/questions/22581946/python-class-inside-class-using-same-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!