使用 Python 3 中调用 super() 的 4 种方法中的哪一种? [英] Which of the 4 ways to call super() in Python 3 to use?
问题描述
我想知道什么时候使用 Python 3 的什么风格 super().
关于模块内置函数中的 super 类的帮助:超级类(对象)|超级()->与 super(__class__, <first argument>) 相同|超级(类型)->未绑定的超级对象|超级(类型,对象)->绑定超级对象;需要 isinstance(obj, type)|super(type, type2) ->绑定超级对象;需要 issubclass(type2, type)
到目前为止,我只使用了 super()
不带参数,它按预期工作(由 Java 开发人员).
问题:
- 在这种情况下,绑定"是什么意思?
- 绑定和未绑定的超级对象有什么区别?
- 什么时候使用
super(type, obj)
,什么时候使用super(type, type2)
? - 像
Mother.__init__(...)
那样命名超类会更好吗?
让我们使用以下类进行演示:
A 类(对象):def m(自我):打印('m')B(A)类:通过
未绑定的 super
对象不会将属性访问分派到类,您必须使用描述符协议:
super
绑定到实例的对象给出绑定方法:
super
绑定到类的对象给出函数(Python 2 中未绑定的方法):
请参阅 Michele Simionato 的关于 Python Super 的知识"博客文章系列(1、2、3) 了解更多信息
I wonder when to use what flavour of 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)
Until now I've used super()
only without arguments and it worked as expected (by a Java developer).
Questions:
- What does "bound" mean in this context?
- What is the difference between bound and unbound super object?
- When to use
super(type, obj)
and whensuper(type, type2)
? - Would it be better to name the super class like in
Mother.__init__(...)
?
Let's use the following classes for demonstration:
class A(object):
def m(self):
print('m')
class B(A): pass
Unbound super
object doesn't dispatch attribute access to class, you have to use descriptor 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
object bound to instance gives bound methods:
>>> super(B, B()).m
<bound method B.m of <__main__.B object at 0xb765dacc>>
>>> super(B, B()).m()
m
super
object bound to class gives function (unbound methods in terms of 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
See Michele Simionato's "Things to Know About Python Super" blog posts series (1, 2, 3) for more information
这篇关于使用 Python 3 中调用 super() 的 4 种方法中的哪一种?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!