考虑以下python代码:
class Parent(object):
def __init__(self, name, serial_number):
self.name = name
self.serial_number = serial_number
class ChildA(Parent):
def __init__(self, name, serial_number):
self.name = name
self.serial_number = serial_number
super(ChildA, self).__init__(name = self.name, serial_number = self.serial_number)
def speak(self):
print("I am from Child A")
class ChildB(Parent):
def __init__(self, name, serial_number):
self.name = name
self.serial_number = serial_number
super(ChildB, self).__init__(name = self.name, serial_number = self.serial_number)
def speak(self):
print("I am from Child B")
class GrandChild(ChildA, ChildB):
def __init__(self, a_name, b_name, a_serial_number, b_serial_number):
self.a_name = a_name
self.b_name = b_name
self.a_serial_number = a_serial_number
self.b_serial_number = b_serial_number
super(GrandChild, self).__init_( something )
在GrandChild中运行super
函数时,格式化__init__
参数的正确方法是什么,以便ChildA和ChildB都能获得正确的参数?
另外,如何从GrandChild类中访问speak
方法的两个不同版本(ChildA的版本和ChildB的版本)?
答案 0 :(得分:3)
所以,当你从孙子那里打电话给super时,孩子会调用__init__
方法,因为super跟随__mro__
属性(父母从左到右,然后祖父母从左到右,然后是曾祖父母,...)
由于chaild的 init 也会调用super,所以所有超级调用都将被链接,调用child b' s __init__
并最终调用父init。 / p>
为了实现这一点,您的界面通常需要保持一致。这就是位置参数需要表示相同的事情,并且按顺序排列。
在不是这种情况的情况下,关键字参数可能会更好。
class Parent:
def __init__(self, name, serial, **kwargs):
self.name = name
self.serial = serial
class ChildA(Parent):
def __init__(self, a_name, a_serial, **kwargs):
self.a_name = a_name
self.a_serial = a_serial
super().__init__(**kwargs)
class ChildB(Parent):
def __init__(self, b_name, b_serial, **kwargs):
self.b_name = b_name
self.b_serial = b_serial
super().__init__(**kwargs)
class GrandChild(ChildA, ChildB):
def __init__(self):
super().__init__(name = "blah", a_name = "a blah", b_name = "b blah", a_serial = 99, b_serial = 99, serial = 30)
另请注意,您的代码名称和序列号在所有类之间被重用为实例属性,而且可能不是您想要的。
答案 1 :(得分:1)