简体   繁体   English

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

[英]Bind method to object runtime late binding

I am aware about late bindings in loop in python, but I cant find way to solve this .我知道 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()

I tried with partial in functools but not get success :(我在functools尝试了partial ,但没有成功:(

When you call a.bar() my_method is invoked and since the for loop has ended the value of method for it is the last element in methods list so you always get "FOO" as result.当你调用a.bar() my_method被调用,因为for循环已经结束的值method ,因为这是在最后一个元素methods列表,让您始终获得"FOO"作为结果。

To check you can add a print statement:要检查您可以添加打印语句:

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

But when I set it directly:但是当我直接设置时:

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

It does work.它确实有效。


Using functools.partial :使用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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM