2011-08-21 43 views
4

可能重複困惑:
Understanding Python super()[巨蟒]:通過超()

B子類A,所以在B的__init__我們應該叫A的__init__這樣的:

class B(A): 
    def __init__(self): 
     A.__init__(self) 

但與super(),我看到了這樣的事情:

class B(A): 
    def __init__(self): 
     super(B, self).__init__() #or super().__init__() 

我的問題是:

  1. 爲什麼不super(B, self).__init__(self)?僅僅因爲返回代理對象是綁定的對象?

  2. 如果我在super中省略第二個參數並且返回代理對象是未綁定的,那麼我應該寫super(B).__init__(self)

+1

許多許多人 - 請先搜索。 [如何做,蟒蛇,超級做正確的事情](http://stackoverflow.com/questions/607186/how-does-pythons-super-do-the-right-thing)[怎麼做-python-3-python-3-python-3-python-3-python-3-python-3-python-3-python-3-python-3-python-3-python-3 -super](http://stackoverflow.com/questions/2771904/usage-of-python-3-super) – agf

回答

5

super()返回基類的一個實例,因此self被隱式傳遞給__init__()像任何其他方法調用。

關於你的第二個問題,這是正確的。調用super()沒有實例作爲第二個參數返回對類本身的引用,而不是從您的子類實例構造的實例。

+0

我想我明白了。謝啦 – Alcott