我知道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
没有成功:(