コード サンプルの実行方法により、何が起こっているのかわかりにくくなっています。ただし、次と同等です。
child_methods = [] # a list of all the methods in `Child`
class Parent(object):
def parent_method(self):
print "parent_method() called"
method = child_methods[0]
method(self)
class Child(Parent):
def child_method(self):
print "child_method() called"
# add child_method to child_methods
child_methods.append(Child.child_method)
ご覧のとおり、child_methods[0]
実際には function になりますChild.child_method
。これはプレーンな関数であり、バインドされたメソッドではありません。のインスタンスに関連付けられていないChild
ため、自分自身を渡すことができ、渡す必要がありself
ます。Child
次のようにして、インスタンスからバインドされたメソッドを取得します。
child_obj = Child()
bound_child_method = child_obj.child_method
これは、インスタンスで見つからない場合、Python がオブジェクトの型で属性を検索するという事実によって不明確になります。例えば:
# A dummy class to hold attributes
class Foo(object):
pass
Foo.bar = 123 # we're adding an attribute to the type itself
foo1 = Foo()
print foo1.bar # prints 123
foo1.bar = 456 # this `bar` attribute "hides" the one on the type
print foo1.bar # prints 456
foo2 = Foo()
print foo2.bar # prints the 123 from the type again
これが、コード サンプルでcommands
が実際には「グローバル」変数であり、のインスタンスを介して紛らわしくアクセスされる理由ですB
。(オブジェクトまたはその子のみがこの変数にアクセスする場合、これは必ずしも悪い習慣ではありませんB
が、ルックアップ ルールはマイナーな落とし穴です。)