Can I use Python 3 super() in Python 2.5.6?
Can I use clean Python 3 super()
synt开发者_JAVA百科ax in Python 2.5.6?
__future__
import?I realize this question is old, and the selected answer may have been correct at the time, but it's no longer complete. You still can't use super()
in 2.5.6, but python-future
provides a back-ported implementation for 2.6+:
Install python-future
with:
% pip install future
The following shows the redefinition of super
under builtins
:
% python
...
>>> import sys
>>> sys.version_info[:3]
(2, 7, 9)
>>>
>>> super
<type 'super'>
>>>
>>> from builtins import *
>>> super
<function newsuper at 0x000000010b4832e0>
>>> super.__module__
'future.builtins.newsuper'
It can be used as follows:
from builtins import super
class Foo(object):
def f(self):
print('foo')
class Bar(Foo):
def f(self):
super().f() # <- whoomp, there it is
print('bar')
b = Bar()
b.f()
which outputs
foo
bar
If you use pylint
, you can disable legacy warnings with the comment:
# pylint: disable=missing-super-argument
You cannot use a bare super()
call that contains no type/class. Nor can you implement a replacement for it that will work. Python 3.x contains special support to enable bare super()
calls (it places a __class__
cell variable in all functions defined within a class - see PEP 3135
Update
As of Python 2.6+, bare super()
calls can be used via the future
Python package. See posita's answer for an explanation.
No you cannot. But you can use Python 2's super()
in Python 3.
Note This is a terrible "solution", I post it only to make sure you don't do this at home!
I repeat: do not do this
One may think about using this mixin
class Super(object):
def super(self):
return super(self.__class__, self)
to obtain a self.super()
:
class A(object, Super):
def __init__(self):
print "A"
class B(A):
def __init__(self):
print "B"
self.super().__init__()
yielding:
>>> a = A()
A
>>> b = B()
B
A
But beware: This self.super()
is not equivalent to super(B, self)
- if A
also called self.super().__init__()
, the construction of a B
would cause the A
constructor to call itself indefinitely, since self.__class__
will remain B
. This is due to the lack of the __class__
mentioned in the accepted answer. You can possibly work around this issue with a hidden state machine or a sophisticated metaclass that e.g. checks the actual class's position in self.__class__.mro()
, but is it really worth it? Probably not...
精彩评论