我可以在 Python 2.5.6 中使用 Python 3 super() 吗?
我可以在 Python 2.5 中使用干净的 Python 3 super()
语法吗? 6?
也许使用某种 __future__ 导入?
Can I use clean Python 3 super()
syntax in Python 2.5.6?
Maybe with some kind of __future__
import?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我意识到这个问题已经很老了,所选的答案当时可能是正确的,但它不再完整。在 2.5.6 中您仍然无法使用
super()
,但是python-future
为 2.6+ 提供向后移植的实现:安装
python-future
具有:下面显示了
builtins
下super
的重新定义:它可以按如下方式使用:
which 输出
如果您使用
pylint
,您可以使用以下命令禁用旧版警告:评论: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, butpython-future
provides a back-ported implementation for 2.6+:Install
python-future
with:The following shows the redefinition of
super
underbuiltins
:It can be used as follows:
which outputs
If you use
pylint
, you can disable legacy warnings with the comment:您不能使用不包含类型/类的裸
super()
调用。您也无法实现有效的替代方案。 Python 3.x 包含对启用裸super()
调用的特殊支持(它将__class__
单元变量放置在类中定义的所有函数中 - 请参阅 PEP 3135更新
从 Python 2.6+ 开始, 裸露
super()
调用可以通过future
Python 包使用。请参阅posita 的回答 进行解释。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 baresuper()
calls (it places a__class__
cell variable in all functions defined within a class - see PEP 3135Update
As of Python 2.6+, bare
super()
calls can be used via thefuture
Python package. See posita's answer for an explanation.不,你不能。但是你可以使用Python 2的
super()
Python 3.No you cannot. But you can use Python 2's
super()
in Python 3.注意这是一个糟糕的“解决方案”,我发布它只是为了确保您不要在家里这样做!
我重复一遍:不要这样做
有人可能会考虑使用这个 mixin
来获取
self.super()
:产生:
但要注意:这
self.super()
不等于super(B, self)
- 如果A
也称为self.super()。 __init__()
,构造一个B
会导致A
构造函数无限期地调用自身,因为self.__class__
将保留为B
。这是由于缺少接受的答案中提到的__class__
。您可以使用隐藏状态机或复杂的元类来解决此问题,例如检查 self.__class__.mro() 中实际类的位置,但这真的值得吗?可能不是...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
to obtain a
self.super()
:yielding:
But beware: This
self.super()
is not equivalent tosuper(B, self)
- ifA
also calledself.super().__init__()
, the construction of aB
would cause theA
constructor to call itself indefinitely, sinceself.__class__
will remainB
. 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 inself.__class__.mro()
, but is it really worth it? Probably not...