所属网站分类: python高级 > 面向对象
有什么区别?
class Child(SomeBaseClass): def __init__(self): super(Child, self).__init__()和
class Child(SomeBaseClass): def __init__(self): SomeBaseClass.__init__(self)我们已经看到super在只有单继承的类中使用了很多,但也可以在多重继承中使用它,那么在这种情况下使用它的优点是什么?
SomeBaseClass.__init__(self)意味着调用SomeBaseClass的__init__。而
super(Child, self).__init__()
表示__init__从Child实例的方法解析顺序(MRO)中的父类调用绑定。
如果实例是Child的子类,则MRO中可能会有另一个父级。
我玩了一下super(),并且认识到我们可以改变呼叫顺序。
例如,我们有下一个层次结构:
A / \ B C \ / D
在这种情况下,D的mro将是(仅适用于Python 3):
In [26]: D.__mro__ Out[26]: (__main__.D, __main__.B, __main__.C, __main__.A, object)让我们创建一个super()执行后调用的类。
In [23]: class A(object): # or with Python 3 can define class A: ...: def __init__(self): ...: print("I'm from A") ...: ...: class B(A): ...: def __init__(self): ...: print("I'm from B") ...: super().__init__() ...: ...: class C(A): ...: def __init__(self): ...: print("I'm from C") ...: super().__init__() ...: ...: class D(B, C): ...: def __init__(self): ...: print("I'm from D") ...: super().__init__() ...: d = D() ...: I'm from D I'm from B I'm from C I'm from A A / ⇖ B ⇒ C ⇖ / D因此我们可以看到解决方案顺序与MRO中的相同。但是当我们super()在方法的开头调用时:
In [21]: class A(object): # or class A: ...: def __init__(self): ...: print("I'm from A") ...: ...: class B(A): ...: def __init__(self): ...: super().__init__() # or super(B, self).__init_() ...: print("I'm from B") ...: ...: class C(A): ...: def __init__(self): ...: super().__init__() ...: print("I'm from C") ...: ...: class D(B, C): ...: def __init__(self): ...: super().__init__() ...: print("I'm from D") ...: d = D() ...: I'm from A I'm from C I'm from B I'm from D我们有一个不同的顺序,它颠倒了MRO元组的顺序。
A / ⇘ B ⇐ C ⇘ / D