2011-10-10 81 views

回答

14

不能使用裸super()呼叫不含類型/類。你也不能實施可以工作的替代品。 Python的3.x中含有特殊的支持,以使裸super()電話(它放置在一個類中定義的所有功能__class__細胞變量 - 見PEP 3135

+1

謝謝。我很困惑,因爲這個PEP的早期版本說你會用'from __future__ import new_super'導入它,這不起作用。 –

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

不錯,謝謝:) –

相關問題