我可以在Python 2.5.6中使用干净的Python 3 super()
语法吗?
也许某种__future__
导入?我可以在Python 2.5.6中使用Python 3 super()吗?
14
A
回答
14
不能使用裸super()
呼叫不含类型/类。你也不能实施可以工作的替代品。 Python的3.x中含有特殊的支持,以使裸super()
电话(它放置在一个类中定义的所有功能__class__
细胞变量 - 见PEP 3135
6
不,你不能。但是你可以使用Python 2的super()
在Python 3
3
注意这是一个可怕的“解决方案”,我把它张贴只!请确保您不这样做在家里
我再说一遍:不这样做
有人可能会考虑使用该混入
class Super(object):
def super(self):
return super(self.__class__, self)
获得self.super()
:
class A(object, Super):
def __init__(self):
print "A"
class B(A):
def __init__(self):
print "B"
self.super().__init__()
产生:
>>> a = A()
A
>>> b = B()
B
A
但要注意:这self.super()
不等同于super(B, self)
- 如果A
也称为self.super().__init__()
,一个B
的建设将导致A
构造函数无限期地自行调用,因为self.__class__
将保持B
。这是由于缺少accepted answer中提到的__class__
。您可以使用隐藏状态机或复杂的元类来解决此问题,例如检查实际班级在self.__class__.mro()
中的位置,但真的值得吗?可能不是...
15
我意识到这个问题已经过时,所选的答案在当时可能是正确的,但它不再完整。您仍然不能使用2.5.6 super()
,但python-future
为2.6+一个back-ported implementation:
% pip install future
...
% python
...
>>> import sys
>>> sys.version_info[:3]
(2, 7, 9)
>>> from builtins import *
>>> super
<function newsuper at 0x000000010b4832e0>
>>> super.__module__
'future.builtins.newsuper'
>>> 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
+0
不错,谢谢:) –
相关问题
- 1. 我可以在giraph中使用python吗?
- 2. 在Python中使用super()
- 3. 我可以在Python 2和Python 3上安装Tensorflow吗?
- 4. 我可以在python 2环境下运行python 3脚本吗?
- 5. 我可以在Python中调用Perl吗?
- 6. 我可以用sshtunnel使用Python Peewee吗?
- 7. 我可以在python 3中进行腌制,然后在python 2中解压吗?
- 8. 我可以使用GAE + python 2.7 + django.utils.translation吗?
- 9. SAP可以使用Python吗?
- 10. 可以调用[super loadView]吗?
- 11. 在python中使用super()方法
- 12. 我可以在python中使用sqlite3以后的版本吗?
- 13. 可以PIL在Python 3(不枕)使用
- 14. 我可以在Python Spreadsheets中使用gspread在Python中编写整行代码吗?
- 15. 在Python类中多次使用super()
- 16. 我可以在python中使用Yed-Graphs上的Graph-Algorithm吗?
- 17. 我可以在python中使用字典作为矩阵吗?
- 18. 你可以在Python 2.4中使用python-daemon吗?
- 19. 在Python中正确使用super - 我应该明确引用类名吗?
- 20. 我可以在Python中使用Google Transliteration吗?
- 21. 我可以在Java或C++中使用Python缩进样式吗?
- 22. 我可以在Python中使用Popen打开的gzip文件吗?
- 23. 我可以在64位python中使用32位dll或exe吗?
- 24. 我可以在Ionic中使用Python作为后端工作吗
- 25. 我们可以在Python中使用return来打印函数吗?
- 26. 我可以在python中使用库抽象吗?
- 27. 我可以在Python Bottle中使用PUT http方法吗?
- 28. 我可以使用Python在App Enging中创建线程吗?
- 29. 我可以在Python 3上提供lxml.etree.parse的URL吗?
- 30. 我可以让Django-oscar在Python 3下工作吗?
谢谢。我很困惑,因为这个PEP的早期版本说你会用'from __future__ import new_super'导入它,这不起作用。 –