gpt4 book ai didi

python - 什么是 python 中的 super (类型)?

转载 作者:太空狗 更新时间:2023-10-30 02:11:24 25 4
gpt4 key购买 nike

类定义:

class A(object):
def foo(self):
print "A"


class B(object):
def foo(self):
print "B"


class C(A, B):
def foo(self):
print "C"

输出:

>>> super(C)
<super: <class 'C'>, NULL>
>>> super(C).foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'super' object has no attribute 'foo'

如果我们不能访问类的属性,那么 super(type) 有什么用?

最佳答案

super(type) 是一个“未绑定(bind)”的 super 对象。 super 上的文档对此进行讨论,但不要真正详细说明“未绑定(bind)” super 对象是什么或做什么。您不能以您尝试使用它们的方式使用它们,这只是语言的一个事实。

这也许就是您想要的:

>>> super(C, C).foo is B.foo
True

也就是说,未绑定(bind)的 super 对象有什么用?我不得不自己查一下,然后找到了一个不错的答案here .但是请注意,这篇文章的结论是 unbound super 是一种语言缺陷,没有实际用途,应该从语言中删除(我同意阅读这篇文章)。文章对unbound super的解释是这样开头的:

Unbound super objects must be turned into bound objects in order to make them to dispatch properly. That can be done via the descriptor protocol. For instance, I can convert super(C1) in a super object bound to c1 in this way:

>>> c1 = C1()
>>> boundsuper = super(C1).__get__(c1, C1) # this is the same as super(C1, c1)

所以,那看起来没什么用,但是文章接着说:

Having established that the unbound syntax does not return unbound methods one might ask what its purpose is. The answer is that super(C) is intended to be used as an attribute in other classes. Then the descriptor magic will automatically convert the unbound syntax in the bound syntax. For instance:

>>> class B(object):
... a = 1
>>> class C(B):
... pass
>>> class D(C):
... sup = super(C)
>>> d = D()
>>> d.sup.a
1

This works since d.sup.a calls super(C).__get__(d,D).a which is turned into super(C, d).a and retrieves B.a.

There is a single use case for the single argument syntax of super that I am aware of, but I think it gives more troubles than advantages. The use case is the implementation of autosuper made by Guido on his essay about new-style classes.

The idea there is to use the unbound super objects as private attributes. For instance, in our example, we could define the private attribute __sup in the class C as the unbound super object super(C):

>>> C._C__sup = super(C)

但是请注意,这篇文章继续描述了这个问题(它并没有完全正确地工作,我认为主要是因为 MRO 依赖于您正在处理的实例的类,因此给定一个实例,某些类 X 的父类(super class)可能会有所不同,具体取决于我们给出的 X 实例)。

关于python - 什么是 python 中的 super (类型)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22550131/

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