代碼示例的完成方式使得有點難以分辨發生了什麼。然而,這等同於:
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]
實際上是功能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
或其子對象訪問此變量,但查找規則是一個小問題,這不一定是壞習慣。)
謝謝。我明白「無約束的方法」需要通過「自我」。 –
準確。如果你添加一個* bound *方法到列表中,使用'child_methods.append(Child()。child_method)',那麼這就沒有必要了 - 它會使用你從它得到的'Child'實例。 – millimoose
這是不一樣的。在問題的代碼中,沒有未綁定的方法訪問。 'method'的值是一個常規函數。 – newacct