我可以在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應用程序中「嵌入」Python後端嗎?
- 15. 我可以在Python Spreadsheets中使用gspread在Python中編寫整行代碼嗎?
- 16. 我可以在python中使用Yed-Graphs上的Graph-Algorithm嗎?
- 17. 在Python類中多次使用super()
- 18. 我可以在python中使用字典作爲矩陣嗎?
- 19. 你可以在Python 2.4中使用python-daemon嗎?
- 20. 我可以在Python 3上提供lxml.etree.parse的URL嗎?
- 21. 我可以讓Django-oscar在Python 3下工作嗎?
- 22. 我可以在Python中使用Google Transliteration嗎?
- 23. 我們可以在Python中使用return來打印函數嗎?
- 24. 我可以在Python Bottle中使用PUT http方法嗎?
- 25. 我可以在Python RegEx中混合使用字符類嗎?
- 26. 我可以在python中使用庫抽象嗎?
- 27. 我可以在Anaconda中使用Ubuntu的默認Python 2.7嗎?
- 28. 我可以在Java或C++中使用Python縮進樣式嗎?
- 29. 我可以使用Python在App Enging中創建線程嗎?
- 30. 我可以在Ionic中使用Python作爲後端工作嗎
謝謝。我很困惑,因爲這個PEP的早期版本說你會用'from __future__ import new_super'導入它,這不起作用。 –