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

17 投票
4 回答
5143 浏览
提问于 2025-04-17 04:03

我可以在 Python 2.5.6 中使用干净的 Python 3 的 super() 语法吗?
也许可以通过某种 __future__ 导入来实现?

4 个回答

6

不,你不能这样做。不过你可以在Python 3中使用Python 2的super()这个功能。

23

我知道这个问题已经很久了,选中的答案在当时可能是正确的,但现在已经不够完整了。在Python 2.5.6中,你仍然不能使用 super(),不过python-future 提供了一个适用于2.6及以上版本的回溯实现

你可以通过以下方式安装 python-future

% pip install future

下面展示了在 builtins 下重新定义 super 的方法:

% 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'

可以这样使用:

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()

这将输出:

foo
bar

如果你使用 pylint,可以通过以下注释来禁用旧版警告:

# pylint: disable=missing-super-argument
15

你不能使用没有指定类型或类的 super() 调用。也不能自己实现一个替代的方法来让它工作。Python 3.x 里有特别的支持,可以让你使用没有参数的 super() 调用(它在类定义的所有函数里放了一个 __class__ 变量 - 具体可以参考 PEP 3135)。


更新

从 Python 2.6 版本开始,你可以通过 future 这个 Python 包来使用没有参数的 super() 调用。想了解更多,可以看看 posita 的回答

撰写回答