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

后端 未结 4 2039
暗喜
暗喜 2020-12-31 05:45

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

class MyDecorator(Decorator):
           


        
相关标签:
4条回答
  • 2020-12-31 06:06

    In Python 3.0, you can use super() which is equivalent to 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)
    
    0 讨论(0)
  • 2020-12-31 06:06

    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
    
    0 讨论(0)
  • 2020-12-31 06:19

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

    def __init__(self):
        super(self.__class__, self)
        ...
    
    0 讨论(0)
  • 2020-12-31 06:28

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

    0 讨论(0)
提交回复
热议问题