这里有一些很好的答案,但它们没有解决在层次结构中的不同类具有不同签名的情况下如何使用super()……特别是在__init__的情况下
为了回答这个问题并能够有效地使用super(),我建议阅读我的答案super()并更改合作方法的签名。
下面是这种情况的解决方案:
层次结构中的顶级类必须继承自自定义类,如SuperObject:
如果类可以接受不同的参数,始终将接收到的所有参数作为关键字参数传递给超函数,并且始终接受**kwargs。
class SuperObject:
def __init__(self, **kwargs):
print('SuperObject')
mro = type(self).__mro__
assert mro[-1] is object
if mro[-2] is not SuperObject:
raise TypeError(
'all top-level classes in this hierarchy must inherit from SuperObject',
'the last class in the MRO should be SuperObject',
f'mro={[cls.__name__ for cls in mro]}'
)
# super().__init__ is guaranteed to be object.__init__
init = super().__init__
init()
使用示例:
class A(SuperObject):
def __init__(self, **kwargs):
print("A")
super(A, self).__init__(**kwargs)
class B(SuperObject):
def __init__(self, **kwargs):
print("B")
super(B, self).__init__(**kwargs)
class C(A):
def __init__(self, age, **kwargs):
print("C",f"age={age}")
super(C, self).__init__(age=age, **kwargs)
class D(B):
def __init__(self, name, **kwargs):
print("D", f"name={name}")
super(D, self).__init__(name=name, **kwargs)
class E(C,D):
def __init__(self, name, age, *args, **kwargs):
print( "E", f"name={name}", f"age={age}")
super(E, self).__init__(name=name, age=age, *args, **kwargs)
E(name='python', age=28)
输出:
E name=python age=28
C age=28
A
D name=python
B
SuperObject