开发者

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


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

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.

[Edit to add to my initial points] Actually, there is another less used way to use super() in Python 2.x. You can use an unbound form of super and have it bound when you access it:

>>> 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. For Python 2.6 and later you could probably wrap this up as a class decorator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜