[英]python dynamically create attributes class
I am facing issues adding class attributes dynamically from a list of strings, consider the following scenario: 我面临从字符串列表中动态添加类属性的问题,请考虑以下情形:
This is my class: 这是我的课:
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")
The issue seems to be the fact that it is treating the attribute name as a string, can someone please advise 问题似乎是因为它将属性名称视为字符串,有人可以建议吗
i = "test"
is actually converted to {'i':'test'}
when passed to **kwargs
inside add_attributes
, so you need to do something like this: i = "test"
传递给add_attributes
内部的**kwargs
时,实际上会转换为{'i':'test'}
,因此您需要执行以下操作:
for i in my_list:
c.add_attributes(**{ i : "test"})
Instead of a for-loop, you could use dict.fromkeys : 除了使用for循环,还可以使用dict.fromkeys :
c.add_attributes(**dict.fromkeys(seq, "test"))
since 以来
In [13]: dict.fromkeys(seq, "test")
Out[13]: {'age': 'test', 'gender': 'test', 'name': 'test'}
The **
tells Python to unpack the dict into keyword arguments. **
告诉Python将dict解压缩为关键字参数。 The syntax is explained here and in the docs, here . 语法在此处和文档中进行了解释。
By the way, it's best not to use list
as a variable name, since it makes it difficult to access the builtin of the same name. 顺便说一句,最好不要将list
用作变量名,因为这样会使访问相同名称的内建函数变得困难。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.