2012-09-25 20 views
4

可能重複:
Why do I have to specify my own class when using super(), and is there a way to get around it?爲什麼它是強制性的給類名,而使用超()在Python

我在讀這本書 - "Core Python Programming",我真的覺得很漂亮我會說。但是當我在研究主題繼承時,我有點困惑。

這本書某處說,我們可以使用super()來調用super class method,它會爲我們找到基類方法,而且我們也不需要通過self明確的,像我們這樣做不超..

這裏的示例代碼: -

# Invoking super class method without super() .. Need to pass `self` as argument 
class Child(Parent): 
    def foo(self): 
     Parent.foo(self) 

# Invoking with super(). 
# No need to pass `self` as argument to foo() 
class Child(Parent1, Parent2): 
    def foo(self): 
     super(Child, self).foo() 
     print 'Hi, I am Child-foo()' 

我的問題是 - 爲什麼我們必須通過classnamesuper()通話。作爲類名可以推斷來自super調用的類d ..

因此,由於super()是從 class Child中調用的,因此classname應該是隱式的。那麼爲什麼我們需要這個?

編輯: - 給Child作爲super()的參數沒有意義,因爲它沒有給出任何信息。我​​們可以使用super(self) ..並且該方法已經在超級它們按照括號內的順序排列。

+4

在Python 3中,你可以使用'super()'。 [Python的super()認爲超級!](http://rhettinger.wordpress.com/2011/05/26/super-considered-super/) – jfs

+0

OOPs。無法訪問該鏈接在辦公室.. :(將看到它回家.. –

回答

4

通過提供類名作爲第一個參數,可以提供冗餘信息。是。這有點愚蠢*,這就是爲什麼在Python 3中super的行爲發生了變化。

*我的答案實際上與John Carter的答案相矛盾。當然,我們中只有一個是對的。我不想冒犯他和其他人,我很高興看到super(C, self).method(arg)在類C :-)中沒有實際使用的有意義的例子。

+0

謝謝1月...我使用Python 2.7。它有一個不同的行爲.. –

+1

你是對的1月我撤回我的初始沒有冒犯地回答。 –

相關問題