【发布时间】:2014-06-17 21:55:12
【问题描述】:
我正在尝试在类中动态声明一个方法。例如:
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