在Python 3中调用super()的4种方法中的哪一种?

dea*_*mon 20 python oop super python-3.x

我想知道什么时候使用Python 3 super()的味道.

Help on class super in module builtins:

class super(object)
 |  super() -> same as super(__class__, <first argument>)
 |  super(type) -> unbound super object
 |  super(type, obj) -> bound super object; requires isinstance(obj, type)
 |  super(type, type2) -> bound super object; requires issubclass(type2, type)
Run Code Online (Sandbox Code Playgroud)

到目前为止,我super()只使用了没有参数,它按预期工作(由Java开发人员).

问题:

  • 在这种情况下,"约束"意味着什么?
  • 绑定和未绑定的超级对象有什么区别?
  • 何时使用super(type, obj)和何时super(type, type2)
  • 如此命名超级类会更好Mother.__init__(...)吗?

Den*_*ach 17

我们使用以下类进行演示:

class A(object):
    def m(self):
        print('m')

class B(A): pass
Run Code Online (Sandbox Code Playgroud)

未绑定super对象不会调度对类的属性访问,您必须使用描述符协议:

>>> super(B).m
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'super' object has no attribute 'm'
>>> super(B).__get__(B(), B)
<super: <class 'B'>, <B object>>
Run Code Online (Sandbox Code Playgroud)

super 绑定到实例的对象提供绑定方法:

>>> super(B, B()).m
<bound method B.m of <__main__.B object at 0xb765dacc>>
>>> super(B, B()).m()
m
Run Code Online (Sandbox Code Playgroud)

super 绑定到类的对象给出了函数(根据Python 2的未绑定方法):

>>> super(B, B).m
<function m at 0xb761482c>
>>> super(B, B).m()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: m() takes exactly 1 positional argument (0 given)
>>> super(B, B).m(B())
m
Run Code Online (Sandbox Code Playgroud)

见米歇尔Simionato的"事情知道的关于Python的超级"博客文章系列(1,2,3)了解更多信息


dan*_*van 7

快速说明,PEP3135 New Super中super概述了新的用法,它是在python 3.0中实现的.特别相关;

super().foo(1, 2)
Run Code Online (Sandbox Code Playgroud)

替换旧的:

super(Foo, self).foo(1, 2)
Run Code Online (Sandbox Code Playgroud)