来自字典的 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:01:47  来源:igfitidea点击:

Python update object from dictionary

pythoniterable-unpacking

提问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 updatemethod as part of MyClassso 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

Also, maybe it would be good style to have a wrapper around the dict's update method:

此外,也许在 dict 的 update 方法周围有一个包装器是一种很好的风格:

def update(self, b):
    self.__dict__.update(b)

PS: Sorry for not commenting at @S.Lott's post but I don't have the rep yet.

PS:很抱歉没有在@ S.Lott的帖子中发表评论,但我还没有代表。

回答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)