Why do I have to specify my own class when using super(), and is there a way to get around it?

耗尽温柔 提交于 2019-12-03 19:50:12

问题


When using Python's super() to do method chaining, you have to explicitly specify your own class, for example:

class MyDecorator(Decorator):
    def decorate(self):
        super(MyDecorator, self).decorate()

I have to specify the name of my class MyDecorator as an argument to super(). This is not DRY. When I rename my class now I will have to rename it twice. Why is this implemented this way? And is there a way to weasel out of having to write the name of the class twice(or more)?


回答1:


The BDFL agrees. See Pep 367 - New Super for 2.6 and PEP 3135 - New Super for 3.0.




回答2:


Your wishes come true:

Just use python 3.0. In it you just use super() and it does super(ThisClass, self).

Documentation here. Code sample from the documentation:

class C(B):
    def method(self, arg):
        super().method(arg)    
        # This does the same thing as: super(C, self).method(arg)



回答3:


This answer is wrong, try:

def _super(cls):
    setattr(cls, '_super', lambda self: super(cls, self))
    return cls

class A(object):
    def f(self):
        print 'A.f'

@_super
class B(A):
    def f(self):
        self._super().f()

@_super
class C(B):
    def f(self):
        self._super().f()

C().f() # maximum recursion error

In Python 2 there is a way using decorator:

def _super(cls):
    setattr(cls, '_super', lambda self: super(cls, self))
    return cls

class A(object):
    def f(self):
        print 'A.f'

@_super
class B(A):
    def f(self):
        self._super().f()

B().f() # >>> A.f



回答4:


you can also avoid writing a concrete class name in older versions of python by using

def __init__(self):
    super(self.__class__, self)
    ...


来源:https://stackoverflow.com/questions/466611/why-do-i-have-to-specify-my-own-class-when-using-super-and-is-there-a-way-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!