gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:19:49 24 4
gpt4 key购买 nike

我想知道什么时候使用什么风格的 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)

直到现在,我只使用了不带参数的 super() 并且它按预期工作(由 Java 开发人员提供)。

问题:

  • 在这种情况下,“绑定(bind)”是什么意思?
  • 绑定(bind)和未绑定(bind) super 对象有什么区别?
  • 何时使用 super(type, obj) 以及何时使用 super(type, type2)
  • Mother.__init__(...) 那样命名父类(super class)会更好吗?

最佳答案

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

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

class B(A): pass

Unbound super 对象不分派(dispatch)对类的属性访问,你必须使用描述符协议(protocol):

>>> 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>>

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

>>> super(B, B()).m
<bound method B.m of <__main__.B object at 0xb765dacc>>
>>> super(B, B()).m()
m
绑定(bind)到类的

super 对象提供函数(就 Python 2 而言是未绑定(bind)方法):

>>> 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

有关详细信息,请参阅 Michele Simionato 的“关于 Python Super 的须知”博客文章系列(123)

关于python - 使用 Python 3 中调用 super() 的 4 种方法中的哪一种?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11290936/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com