21

Python 3 super()のどのフレーバーをいつ使用するのだろうか。

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__(...)か?
4

2 に答える 2

18

デモンストレーションに次のクラスを使用しましょう。

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

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

詳細については、Michele Simionato の「Things to Know About Python Super」ブログ投稿シリーズ ( 123 ) を参照してください。

于 2010-05-05T13:28:15.797 に答える