动态地在类中声明方法

时间:2014-05-01 12:11:06

标签: python

我正在尝试动态地在类中声明一个方法。例如:

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 ...

还有另一种解决方案吗?

干杯

1 个答案:

答案 0 :(得分:2)

方法就是对象,就像Python中的任何其他值一样:

class Foo(object):
    def __init__(self, a, b, c):
        self.a = lambda: a
        # or
        def b_():
            return b
        self.b = b_