【问题标题】:Declare method inside class dynamically [duplicate]动态声明类内的方法[重复]
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 谢谢!我使用 lambda 而不是 exec 并且工作完美!
猜你喜欢
  • 2020-07-12
  • 2017-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-24
相关资源
最近更新 更多