可正常工作:爲什麼classmethod的super需要第二個參數?
>>> class Foo(object):
... @classmethod
... def hello(cls):
... print 'hello, foo'
...
>>> class Bar(Foo):
... @classmethod
... def hello(cls):
... print 'hello, bar'
... super(Bar, cls).hello()
...
>>> b = Bar()
>>> b.hello()
hello, bar
hello, foo
我也可以調用基類明確:
>>> class Bar(Foo):
... @classmethod
... def hello(cls):
... print 'hello, bar'
... Foo.hello()
...
>>> b = Bar()
>>> b.hello()
hello, bar
hello, foo
我想知道爲什麼我不能省略的第一個參數super
,像這樣:
>>> class Bar(Foo):
... @classmethod
... def hello(cls):
... print 'hello, bar'
... super(Bar).hello()
...
>>> b = Bar()
>>> b.hello()
hello, bar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in hello
AttributeError: 'super' object has no attribute 'hello'
當沒有第二個參數的super
調用的結果看起來像是一個超類型的類類型:
>>> class Bar(Foo):
... @classmethod
... def hello(cls):
... print Foo, type(Foo)
... print super(Bar), type(super(Bar))
... print cls, type(cls)
...
>>> b = Bar()
>>> b.hello()
<class '__main__.Foo'> <type 'type'>
<super: <class 'Bar'>, NULL> <type 'super'>
<class '__main__.Bar'> <type 'type'>
我想我只是想知道這裏的設計。爲什麼我需要將類對象傳入超級調用以獲取對基類類型Foo
的引用?對於常規方法,將self
傳遞給函數是有意義的,因爲它需要將基類類型綁定到該類的實際實例。但是classmethod不需要該類的特定實例。
編輯: 我得到的Python 3.2相同的錯誤,因爲我在上面2.7 super(Bar).hello()
做。不過,我可以簡單地做super().hello()
,這工作正常。
在python 3.x中它們修復了超級調用...在python2x中,它們只是沒有認爲它通過那麼多(我的猜測是......)無論如何,我認爲這將最終關閉如「爲什麼」的問題通常是... –
您可能會發現這個有用:http://stackoverflow.com/questions/11354786/super-confusing-python-multiple-inheritance-super?rq=1 – mdscruggs
@JoranBeasley咩,我已經問過幾個爲什麼類型的問題還沒有結束。 – jterrace