[英]Add key to dict with setattr() in Python
How can I add a key to an object's dictionary with setattr()
? 如何使用
setattr()
将对象的字典添加到对象的字典中? Say I have the fields
dictionary defined in my class. 说我在班上定义了
fields
字典。 From another class I would like to add a key to this dictionary. 从另一个类我想在这本词典中添加一个键。 How do I proceed?
我该怎么办?
setattr(cls, 'fields', 'value')
changes the attribute entirely. setattr(cls, 'fields', 'value')
完全改变了属性。
你不需要,如果你需要沿着名称查找路线,那么你使用:
getattr(cls, 'fields')['key'] = 'value'
You should use getattr
instead of setattr
to do this. 您应该使用
getattr
而不是setattr
来执行此操作。 Something like. 就像是。
>>> class TestClass:
def __init__(self):
self.testDict = {}
>>> m = TestClass()
>>> m.testDict
{}
>>> getattr(m, "testDict")["key"] = "value"
>>> m.testDict
{'key': 'value'}
cls.fields['key'] = 'value'
怎么样?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.