Declare method inside class dynamically
本问题已经有最佳答案,请猛点这里访问。
我试图在类内动态声明一个方法。例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Foo (object): def __init__ (self): super(Foo, self).__init__() dict_reference = {a:1, b:2, c:3} # This will add atributes a,b and c ... self.__dict__.update(dict_reference) # ... but I want methods instead, like self.a() return 1 d = {} for k in dict_reference.keys(): exec"def {method_name}(): return {data}".format(method_name=k, data=dict_reference[k]) in d del d['__builtins__'] self.__dict__.update(d) # That's the only solution I found so far ... |
还有其他解决方案吗?
干杯
方法也是对象,与Python中的任何其他值一样:
1 2 3 4 5 6 7 | class Foo(object): def __init__(self, a, b, c): self.a = lambda: a # or def b_(): return b self.b = b_ |