考虑我有以下字典:
dic={}
dic["var1"]=val1
dic["var2"]=val2
现在我有另一个包含两个属性的对象:var1
和var2
。
我想在对象的方法中运行一个循环,如(伪代码):
for key, value in dic
self.key=value
以便self.var1=val2
和self.var2=val2
如何在python中实现它?
梅尔
答案 0 :(得分:3)
>>> class Obj(object):
... pass
...
>>> obj = Obj()
>>> for key, value in {'var1':5, 'var2':6}.iteritems():
... setattr(obj, key, value)
...
>>> obj.var1
5
>>> obj.var2
6
在这里,我有义务说“为什么不使用字典?”
答案 1 :(得分:2)
您可以使用“setattr”:
class Test:
var1 = "Cheese"
var2 = "Toast"
dic = {}
dic["var1"] = "NewCheese"
dic["var2"] = "NewToast"
oTest = Test()
for key in dic.keys():
setattr(oTest, key, dic[key])
print "Var1 = ", oTest.var1
print "Var2 = ", oTest.var2
#
# Result
#
# Var1 = NewCheese
# Var2 = NewToast
#
答案 2 :(得分:2)
您可以更新内部__dict__属性,该属性是包含对象所有成员的字典。
class MyObj:
def __init__(self, member_dict):
self.__dict__.update(member_dict)
dic={}
dic["var1"]=val1
dic["var2"]=val2
obj = MyObj(dic)
print obj.var1
>>> val1
print obj.var2
>>> val2