在同一方法中使用两种 parents 方法
Use both parents methods in the same method
我有一个名为 Cyborg 的 class,它继承自另外两个 classes:Human 和机器人。
假设这两个 parents 有自己的方法 Talk(),我可以从 Cyborg child 调用这两个方法吗?例如:
class Cyborg(Human, Robot):
def Talk(self):
human_properties = Human.Talk()
robot_properties = Robot.Talk()
return human_properties + robot_properties
super() 方法无法解决该问题。
与其将 Talk
视为一种方法,不如将其作为 classmethod
实现,从而消除了首先继承的需要:
class Human:
@classmethod
def Talk(cls, *args):
return
class Robot:
@classmethod
def Talk(cls, *args):
return
class Cyborg:
def Talk(self):
return Human.Talk() + Robot.Talk()
使用 super()
您将在 MRO 链中选取第一个同名方法,但不会同时选取这两个方法(除非选取的方法自己调用 super()
)。如果您想同时选择它们,则必须手动调用它们并显式传递 self
参考:
class Cyborg(Human, Robot):
def Talk(self):
human_properties = Human.Talk(self)
robot_properties = Robot.Talk(self)
return human_properties + robot_properties
无论如何我都建议不要使用多重继承——虽然它很漂亮而且有用,而且在极少数情况下是不可替代的,但它有很多陷阱,处理它是不值得的...
如果您正确地实现了您的继承图,这可以通过 super
来完成。为此,Human
和 Robot
都需要一个共同的基础 class 可以 Talk
.
class Thing:
def Talk(self):
# Things don't talk, but some more complex things may
return ''
class Robot(Thing):
def Talk(self):
return 'I am a computer!\n' + super().Talk()
class Human(Thing):
def Talk(self):
return 'I am an organic being!\n' + super().Talk()
class Cyborg(Human, Robot):
def Talk(self):
return super().Talk()
这是一个会说话的例子。
>>> Cyborg().Talk()
I am an organic being!
I am a computer!
>>> Robot().Talk()
I am a computer!
>>> Human().Talk()
I am an organic being!
我有一个名为 Cyborg 的 class,它继承自另外两个 classes:Human 和机器人。 假设这两个 parents 有自己的方法 Talk(),我可以从 Cyborg child 调用这两个方法吗?例如:
class Cyborg(Human, Robot):
def Talk(self):
human_properties = Human.Talk()
robot_properties = Robot.Talk()
return human_properties + robot_properties
super() 方法无法解决该问题。
与其将 Talk
视为一种方法,不如将其作为 classmethod
实现,从而消除了首先继承的需要:
class Human:
@classmethod
def Talk(cls, *args):
return
class Robot:
@classmethod
def Talk(cls, *args):
return
class Cyborg:
def Talk(self):
return Human.Talk() + Robot.Talk()
使用 super()
您将在 MRO 链中选取第一个同名方法,但不会同时选取这两个方法(除非选取的方法自己调用 super()
)。如果您想同时选择它们,则必须手动调用它们并显式传递 self
参考:
class Cyborg(Human, Robot):
def Talk(self):
human_properties = Human.Talk(self)
robot_properties = Robot.Talk(self)
return human_properties + robot_properties
无论如何我都建议不要使用多重继承——虽然它很漂亮而且有用,而且在极少数情况下是不可替代的,但它有很多陷阱,处理它是不值得的...
如果您正确地实现了您的继承图,这可以通过 super
来完成。为此,Human
和 Robot
都需要一个共同的基础 class 可以 Talk
.
class Thing:
def Talk(self):
# Things don't talk, but some more complex things may
return ''
class Robot(Thing):
def Talk(self):
return 'I am a computer!\n' + super().Talk()
class Human(Thing):
def Talk(self):
return 'I am an organic being!\n' + super().Talk()
class Cyborg(Human, Robot):
def Talk(self):
return super().Talk()
这是一个会说话的例子。
>>> Cyborg().Talk()
I am an organic being!
I am a computer!
>>> Robot().Talk()
I am a computer!
>>> Human().Talk()
I am an organic being!