gpt4 book ai didi

python - 使绑定(bind)方法像函数一样运行的最pythonic方法是什么?

转载 作者:太空狗 更新时间:2023-10-30 02:14:33 25 4
gpt4 key购买 nike

我正在使用一个 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>

最佳答案

传入绑定(bind)到实例的方法是否有效?如果是这样,您无需执行任何特殊操作。

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

关于python - 使绑定(bind)方法像函数一样运行的最pythonic方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/490429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com