Nic*_*ick 4 python methods closures function
我正在使用Python API,希望我将它传递给函数.但是,由于各种原因,我想传递一个方法,因为我希望函数的行为不同,具体取决于它所属的实例.如果我传递一个方法,API将不会使用正确的'self'参数调用它,所以我想知道如何将方法转换为一个知道它属于'self'的函数.
我可以想到有几种方法可以做到这一点,包括使用lambda和闭包.我在下面列举了一些这样的例子,但我想知道是否有一种达到同样效果的标准机制.
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>
Run Code Online (Sandbox Code Playgroud)
将绑定到实例的方法传入工作吗?如果是这样,您不必做任何特别的事情.
In [2]: class C(object):
...: def method(self, a, b, c):
...: print a, b, c
...:
...:
In [3]: def api_function(a_func):
...: a_func("One Fish", "Two Fish", "Blue Fish")
...:
...:
In [4]: c = C()
In [5]: api_function(c.method)
One Fish Two Fish Blue Fish
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
348 次 |
| 最近记录: |