Why do I have to specify my own class when using super(), and is there a way to get around it?
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)
The BDFL agrees. See PEP 3135 - New Super for Python 3.0 (and Pep 367 - New Super for Python 2.6).
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