简体   繁体   中英

Add key to dict with setattr() in Python

How can I add a key to an object's dictionary with setattr() ? Say I have the fields dictionary defined in my class. 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.

你不需要,如果你需要沿着名称查找路线,那么你使用:

getattr(cls, 'fields')['key'] = 'value'

You should use getattr instead of setattr to do this. 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'怎么样?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM