来自字典的 Python 更新对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/405489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python update object from dictionary
提问by chakrit
Is there a built-in function/operator I could use to unpack values from a dictionary and assign it into instance variables?
是否有内置函数/运算符可用于从字典中解压缩值并将其分配给实例变量?
This is what I intend to do:
这是我打算做的:
c = MyClass()
c.foo = 123
c.bar = 123
# c.foo == 123 and c.bar == 123
d = {'bar': 456}
c.update(d)
# c.foo == 123 and c.bar == 456
Something akin to dictionary update()
which load values from another dictionary but for plain object/class instance?
类似于update()
从另一个字典加载值但用于普通对象/类实例的字典?
回答by Jehiah
there is also another way of doing it by looping through the items in d. this doesn't have the same assuption that they will get stored in c.__dict__
which isn't always true.
还有另一种方法是循环遍历 d 中的项目。这与它们将被存储在c.__dict__
其中的假设不同,这并不总是正确的。
d = {'bar': 456}
for key,value in d.items():
setattr(c,key,value)
or you could write a update
method as part of MyClass
so that c.update(d)
works like you expected it to.
或者您可以编写一个update
方法作为其中的一部分,MyClass
以便按照c.update(d)
您的预期工作。
def update(self,newdata):
for key,value in newdata.items():
setattr(self,key,value)
check out the help for setattr
查看 setattr 的帮助
setattr(...) setattr(object, name, value) Set a named attribute on an object; setattr(x, 'y', v) is equivalent to ''x.y = v''.
setattr(...) setattr(object, name, value) Set a named attribute on an object; setattr(x, 'y', v) is equivalent to ''x.y = v''.
回答by S.Lott
Have you tried
你有没有尝试过
f.__dict__.update( b )
?
?
回答by hyperboreean
回答by Trong Pham
You can try doing:
你可以尝试这样做:
def to_object(my_object, my_dict):
for key, value in my_dict.items():
attr = getattr(my_object, key)
if hasattr(attr, '__dict__'):
to_object(attr, value)
else:
setattr(my_object, key, value)
obj = MyObject()
data = {'a': 1, 'b': 2}
to_object(obj, data)