python - 动态实例属性

标签 python class attributes

假设我有一个类:

class Foo(object):
    def __init__(self,d):
        self.d=d

d={'a':1,'b':2}

inst=Foo(d)

inst.d
Out[315]: {'a': 1, 'b': 2}

有没有办法动态地创建 n 个属性,其中每个属性都是一个字典键,所以 inst.a 会返回 1 等等。

最佳答案

class Foo(object):
    def __init__(self, attributes):
        self.__dict__.update(attributes)

这样就可以了。

>>>foo = Foo({'a': 42, 'b': 999})
>>>foo.a
42
>>>foo.b
999

您还可以使用 setattr 内置方法:

class Foo(object):
    def __init__(self, attributes):
        for attr, value in attributes.iteritems():
            setattr(self, attr, value)

关于python - 动态实例属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12806621/

相关文章:

Python turtle 滚动条

javascript - 脚本标签中属性的顺序重要吗?

python - echo json 到文本文件删除双引号

python - 为什么表达包含 '\' 的正则表达式在没有原始字符串的情况下也能工作。

python - 在 Python 中分配类 bool 值

c# - 将 Lambda 表达式声明为类常量字段

android - 使用 fragment 时应用程序崩溃

c# - 覆盖属性属性

css - 在 div 中定位自定义属性

python - Maya Python : mel. eval(invertSelection;) 不起作用