【问题标题】:Using super() In class that inherits from object在从对象继承的类中使用 super()
【发布时间】:2017-12-17 10:50:52
【问题描述】:

我看过一个像下面这样的课程:

from __future__ import print_function

class MyClass(object):
    def __init__(self):
        super(MyClass, self).__init__()

为什么我们可以在继承自object 的类中使用super?这是正确的方法吗?

【问题讨论】:

  • 你为什么不能呢?最好始终使用super,否则在多重继承上下文中事情会开始出错。

标签: python python-2.7 python-3.x oop


【解决方案1】:

是的,这是正确的方法,因为多重继承使得MyClass 可能最终位于 MRO 中的不同位置:

>>> class MyClass(object):
...     def __init__(self):
...         super(MyClass, self).__init__()
...
>>> class Foo(object):
...     def __init__(self):
...         print('Foo __init__!')
...         super(Foo, self).__init__()
...
>>> class Bar(MyClass, Foo):
...     pass
...
>>> Bar.__mro__
(<class '__main__.Bar'>, <class '__main__.MyClass'>, <class '__main__.Foo'>, <class 'object'>)

这里Bar 继承自MyClass 和Foo,将Foo 放在object 之前。因为,MyClass.__init__() 正在做正确的事情并通过super() 传递__init__ 链,所以Foo.__init__ 被正确调用:

>>> Bar()
Foo __init__!
<__main__.Bar object at 0x107155da0>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 1970-01-01
    • 2011-04-09
    • 2018-02-19
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多