所属网站分类: python 高级 > 面向对象
链接: http://www.pythonheidong.com/blog/article/74/
有什么区别?
- 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
来源: http://www.bubuko.com/infodetail-3048376.html