python动态创建属性类

时间:2014-02-14 12:50:23

标签: python

我面临从字符串列表中动态添加类属性的问题,请考虑以下情况:

这是我的班级:

class Customer(object):
    def __init__(self,**kw):
        self.__dict__ = kw

    def add_attributes(self,**kw):
        self.__dict__.update(kw)  

#a group of attributes i want to associate with the class
list = []
list.append("name")
list.append("age")
list.append("gender")

Customer c

for i in list:
    # i is the attribute name for the class
    c.add_attributes( i = "test")

问题似乎是它将属性名称视为字符串,有人可以建议

3 个答案:

答案 0 :(得分:2)

i = "test"在传递给{'i':'test'}内的**kwargs时实际转换为add_attributes,因此您需要执行以下操作:

for i in my_list:
    c.add_attributes(**{ i : "test"})

答案 1 :(得分:1)

您可以使用setattr内置方法,而不是直接更新__dict__:

for i in list:
    # i is the attribute name for the class
    setattr(c, i, "test")

在我看来,玩内部属性应该是最后的选择。

答案 2 :(得分:0)

您可以使用dict.fromkeys

代替for循环
c.add_attributes(**dict.fromkeys(seq, "test"))

因为

In [13]: dict.fromkeys(seq, "test")
Out[13]: {'age': 'test', 'gender': 'test', 'name': 'test'}

**告诉Python将dict解压缩为关键字参数。 语法在heredocs, here中解释。


顺便说一句,最好不要将list用作变量名,因为它很难访问同名的内置函数。