简体   繁体   English

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

[英]Shortcut for super(type(self), self)

I often do this when overriding a method in a sub class: 在子类中重写方法时,我经常这样做:

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

    [Some extra code]
    return x

My question is: Is there a short cut for super(type(self), self) ? 我的问题是:super(type(self),self)是否有捷径?

Don't do that: if super could just use type(self) as its first argument then it wouldn't have been written to take two arguments in the first place. 不要这样做:如果super可以仅将type(self)用作其第一个参数,那么它就不会被编写为首先接受两个参数。 You must pass the actual class here not an expression which could change if the class has been subclassed. 您必须在此处传递实际的类,而不是如果该类已被子类化的表达式可能会更改的表达式。

The first argument to super needs to be the class containing the current method definition as you are telling super where in the list of bases to start its search. super的第一个参数必须是包含当前方法定义的类,因为您要告诉super在基础列表中从哪里开始搜索。

Python 3 knows about this and treats super() magically at compile time, but in Python 2.x it is just an ordinary function so it has no way to figure out those parameters for itself. Python 3知道这一点,并在编译时神奇地对待了super() ,但是在Python 2.x中,它只是一个普通的函数,因此它无法自行找出这些参数。

[Edit to add to my initial points] Actually, there is another less used way to use super() in Python 2.x. [编辑以补充我的主要观点]实际上,在Python 2.x中还有另一种较少使用的方法来使用super() You can use an unbound form of super and have it bound when you access it: 您可以使用super的未绑定形式,并在访问它时将其绑定:

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

There is an important catch here: you have to use a different name to store each super object, which you can do by using self.__super , but you can't create an unbound super directly in the class definition (because you cannot name the class if it doesn't yet exist) and if you create it outside you have to manually obfuscate the name to ensure you set the correct __super object for the class. 这里有一个重要的问题:您必须使用不同的名称来存储每个super对象,这可以通过使用self.__super ,但是您不能直接在类定义中创建未绑定的super (因为您无法命名类(如果尚不存在),并且如果您在外部创建它,则必须手动混淆名称,以确保为该类设置了正确的__super对象。 For Python 2.6 and later you could probably wrap this up as a class decorator. 对于Python 2.6和更高版本,您可以将其包装为类装饰器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM