我可以在Python 2.5.6中使用Python 3 super()吗?

Dan*_*mov 15 python super python-2.5 python-3.x

我可以super()在Python 2.5.6中使用干净的Python 3 语法吗?
也许有某种__future__进口?

pos*_*ita 22

我意识到这个问题已经过时了,所选答案可能在当时是正确的,但它已不再完整.您仍然无法super()在2.5.6中使用,但为2.6+ python-future提供了后端实现:

安装时间python-future:

% pip install future
Run Code Online (Sandbox Code Playgroud)

下面显示的重新定义superbuiltins:

% 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'
Run Code Online (Sandbox Code Playgroud)

它可以使用如下:

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()
Run Code Online (Sandbox Code Playgroud)

哪个输出

foo
bar
Run Code Online (Sandbox Code Playgroud)

如果使用pylint,您可以使用注释禁用旧版警告:

# pylint: disable=missing-super-argument
Run Code Online (Sandbox Code Playgroud)


don*_*mus 15

您不能使用不super()包含类型/类的裸调用.你也不能实现替代它的工作.Python 3.x包含对启用裸super()调用的特殊支持(它将一个__class__单元变量放在一个类中定义的所有函数中 - 参见PEP 3135


更新

从Python 2.6+开始,可以通过Python包使用裸super()调用.请参阅posita的答案以获得解释.future

  • 谢谢.我感到很困惑,因为这个PEP的早期版本说你用`from __future__ import new_super`导入它,这是行不通的. (2认同)

rob*_*ert 6

你不能.但是你可以super()在Python 3中使用Python 2 .