我正在使用一個Python API,期望我通過它的一個函數。但是,由於各種原因,我想傳遞一個方法,因爲我希望函數的行爲有所不同,具體取決於它所屬的實例。如果我傳遞一個方法,API不會用正確的'self'參數調用它,所以我想知道如何將一個方法變成一個知道它屬於哪個「自我」的函數。使綁定方法像函數一樣起作用的最pythonic方法是什麼?
有幾種方法可以做到這一點,包括使用lambda和closure。我在下面列出了一些例子,但我想知道是否有一個標準的機制來實現相同的效果。
class A(object):
def hello(self, salutation):
print('%s, my name is %s' % (salutation, str(self)))
def bind_hello1(self):
return lambda x: self.hello(x)
def bind_hello2(self):
def hello2(*args):
self.hello(*args)
return hello2
>>> a1, a2 = A(), A()
>>> a1.hello('Greetings'); a2.hello('Greetings')
Greetings, my name is <__main__.A object at 0x71570>
Greetings, my name is <__main__.A object at 0x71590>
>>> f1, f2 = a1.bind_hello1(), a2.bind_hello1()
>>> f1('Salutations'); f2('Salutations')
Salutations, my name is <__main__.A object at 0x71570>
Salutations, my name is <__main__.A object at 0x71590>
>>> f1, f2 = a1.bind_hello2(), a2.bind_hello2()
>>> f1('Aloha'); f2('Aloha')
Aloha, my name is <__main__.A object at 0x71570>
Aloha, my name is <__main__.A object at 0x71590>
呃......我是個白癡。這樣可行。 – Nick 2009-01-29 04:16:07