我想知道什么时候使用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开发人员)工作正常.

Questions:

  • 在这种情况下,"绑定"是什么意思?
  • 绑定和未绑定的超级对象之间有什么区别?
  • 何时使用super(type, obj),何时使用super(type, type2)
  • 把超级班命名为Mother.__init__(...)会更好吗?

推荐答案

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

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

class B(A): pass

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

super对象绑定到实例给出绑定方法:

>>> super(B, B()).m
<bound method B.m of <__main__.B object at 0xb765dacc>>
>>> super(B, B()).m()
m

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

有关更多信息,请参阅Michele Simionato的"关于Python Super的知识"博客文章系列(123)

Python-3.x相关问答推荐

如何在Django中创建两个不同权限的用户?

math. gcd背后的算法是什么,为什么它是更快的欧几里得算法?

在Python代码中包含NAN值时,以两个矩阵计算RMSE

Python - 根据条件附加 NULL 值

将水平堆叠的数据排列成垂直

如何在不使用循环的情况下根据另一个数组的索引值将 numpy 数组中不同通道的值设置为零?

如何使用 django rest 框架在 self forienkey 中删除多达 n 种类型的数据?

正则表达式来识别用 Python 写成单词的数字?

如何使用 regex sub 根据列表中的变量替换字符

是否将dict转换为一个数据帧,每个值都有重复的键?

判断是否存在大文件而不下载它

从 Python2 到 Python3 的这种解包行为的变化是什么?

python3:字节与字节数组,并转换为字符串和从字符串转换

使用 distutils 分发预编译的 python 扩展模块

如何从同一文件夹中的模块导入功能?

try 注释散列变量时,ABCMeta对象不可下标

如何在 Selenium 和 Python 中使用类型查找元素

对字节进行按位运算

从 csv 中删除单行而不复制文件

有没有办法在多个线程中使用 asyncio.Queue ?