1

我知道python循环中的后期绑定,但我找不到解决这个问题的方法。

def bind_method(object, methods):

    for method in methods:
        def my_method():
            result = method()

            return result

        setattr(object, method.__name__, my_method)

def test():
    class A: pass

    def bar(): 
        return "BAR"

    def foo(): 
        return "FOO"

    a = A()
    bind_method(a, [bar, foo])

    assert a.foo() == "FOO"
    assert a.bar() == "BAR"


if __name__ == "__main__":
    test()

我尝试过partialfunctools没有成功:(

4

1 回答 1

1

当你调用a.bar() my_method被调用时,由于 for 循环已经结束,method它的值是列表中的最后一个元素,methods所以你总是得到"FOO"结果。

要检查您可以添加打印语句:

def my_method():
    print(method.__name__) # this will always print `foo`
    result = method()

但是当我直接设置时:

def bind_method(object, methods):
    for method in methods:
        setattr(object, method.__name__, method)

它确实有效。


使用functools.partial

from functools import partial

def bind_method(object, methods):

    for method in methods:
        def my_method(a_method):
            print(a_method.__name__) # this print correct method name
            result = a_method()
            return result

        setattr(object, method.__name__, partial(my_method, method))
于 2016-04-29T14:08:46.477 回答