绑定方法到对象运行时后期绑定

时间:2016-04-29 14:00:53

标签: python functools lexical-closures

我知道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()

我在partial中尝试使用functools但未获得成功:(

1 个答案:

答案 0 :(得分: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))