[英]python dynamically create attributes 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")
問題似乎是因為它將屬性名稱視為字符串,有人可以建議嗎
i = "test"
傳遞給add_attributes
內部的**kwargs
時,實際上會轉換為{'i':'test'}
,因此您需要執行以下操作:
for i in my_list:
c.add_attributes(**{ i : "test"})
您可以使用setattr內置方法來代替直接更新__dict__:
for i in list:
# i is the attribute name for the class
setattr(c, i, "test")
我認為,發揮內部屬性應該是最后的選擇。
除了使用for循環,還可以使用dict.fromkeys :
c.add_attributes(**dict.fromkeys(seq, "test"))
以來
In [13]: dict.fromkeys(seq, "test")
Out[13]: {'age': 'test', 'gender': 'test', 'name': 'test'}
**
告訴Python將dict解壓縮為關鍵字參數。 語法在此處和文檔中進行了解釋。
順便說一句,最好不要將list
用作變量名,因為這樣會使訪問相同名稱的內建函數變得困難。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.