gpt4 book ai didi

python - super(type(self), self) 的快捷方式

转载 作者:太空狗 更新时间:2023-10-29 20:40:09 36 4
gpt4 key购买 nike

我经常在重写子类中的方法时这样做:

def method_x(self):
x = super(type(self), self).method_x()

[Some extra code]
return x

我的问题是:super(type(self), self) 有捷径吗?

最佳答案

不要那样做:如果 super 可以只使用 type(self) 作为它的第一个参数,那么它就不会被写成在第一名。您必须在此处传递实际类,而不是表达式,如果类已被子类化,表达式可能会发生变化。

super 的第一个参数需要是包含当前方法定义的类,因为您要告诉 super 在碱基列表中的何处开始搜索。

Python 3 知道这一点并在编译时神奇地处理 super(),但在 Python 2.x 中它只是一个普通函数,因此它无法自己找出这些参数。

[编辑添加到我的初始点]实际上,在 Python 2.x 中还有另一种不太常用的方法来使用 super()。您可以使用 super 的未绑定(bind)形式,并在您访问它时绑定(bind)它:

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


>>> class B(A):
def foo(self):
self.__super.foo()
print "B.foo"


>>> B._B__super = super(B)
>>> class C(A):
def foo(self):
self.__super.foo()
print "C.foo"


>>> C._C__super = super(C)
>>> class D(C,B): pass

>>> D._D__super = super(D)
>>> D().foo()
A.foo
B.foo
C.foo

这里有一个重要的问题:您必须使用不同的名称来存储每个 super 对象,您可以使用 self.__super 来实现,但您可以不要直接在类定义中创建未绑定(bind)的super(因为如果类不存在则无法命名),如果在外部创建它,则必须手动混淆名称以确保设置该类的正确 __super 对象。对于 Python 2.6 及更高版本,您可能会将其包装为类装饰器。

关于python - super(type(self), self) 的快捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4883822/

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