2010-05-05 40 views
20

我想知道什麼時候使用什麼Python 3 super()。Python 3超級用法()

Help on class super in module builtins: 

class super(object) 
| super() -> same as super(__class__, <first argument>) 
| super(type) -> unbound super object 
| super(type, obj) -> bound super object; requires isinstance(obj, type) 
| super(type, type2) -> bound super object; requires issubclass(type2, type) 

直到現在我用super()唯一沒有爭論和它的工作如預期(由Java開發者)。

問題:

  • 什麼是 「綁定」 在這方面是什麼意思?
  • 綁定和非綁定超級對象有什麼區別?
  • 何時使用super(type, obj)以及何時super(type, type2)
  • Mother.__init__(...)那樣命名超類會更好嗎?

回答

17

讓我們用下面的類演示:

class A(object): 
    def m(self): 
     print('m') 

class B(A): pass 

沒有限制super對象不會調度類屬性的訪問,你必須使用描述協議:

>>> super(B).m 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: 'super' object has no attribute 'm' 
>>> super(B).__get__(B(), B) 
<super: <class 'B'>, <B object>> 

super對象綁定以實例給出綁定方法:

>>> super(B, B()).m 
<bound method B.m of <__main__.B object at 0xb765dacc>> 
>>> super(B, B()).m() 
m 
0123勢必類

super對象給出函數(非綁定方法在Python 2項):

>>> super(B, B).m 
<function m at 0xb761482c> 
>>> super(B, B).m() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: m() takes exactly 1 positional argument (0 given) 
>>> super(B, B).m(B()) 
m 

見米歇爾Simionato的 「事情知道的關於Python的超級」 博客文章系列(123)更多信息

+0

的問題是,特別是約Python3,但Simionato的博客文章系列是關於Python2,並註明*的好處是,你避免重複的名稱類,因爲該名稱隱藏在私有名稱的加密機制中。在Python3中這不再是真的,所以至少有一個優點是過時的。 – gerrit 2016-11-10 12:11:09

7

快速注意,super的新用法在PEP3135 New Super中概述,它在python 3.0中實現。特別重要;

super().foo(1, 2) 

,以取代舊:

super(Foo, self).foo(1, 2)