Python里面的Class使用相同的方法 [英] 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 calculate(self):
variable = 5
return variable
我必须在两个类中声明这个方法,或者我只能在Master中声明它,然后在Child中使用它?
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?
推荐答案
将一个类嵌套在另一个类中没有其他效果,外部类。它们没有其他关系。
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.
换句话说, Child
是一个类,可以作为 Master.Child
而不是纯粹 Child
。 Master
的实例可以寻址 self.Child
,这是对同一类的引用。
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
Master
和 Child 现在有一个
计算
方法。
由于Python支持多重继承,所以创建一个这样的mixin类来共享方法是相对无痛的,并不排除使用其他类来表示is-a关系。
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.
保留实例的包含关系;给您主
一个子
属性并将其设置为子
instance。
Leave containment relationships to instances; give your Master
a child
attribute and set that to a Child
instance.
这篇关于Python里面的Class使用相同的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!