How to assign a new class attribute via __dict__?

前端 未结 1 717
遇见更好的自我
遇见更好的自我 2020-12-01 05:49

I want to assign a class attribute via a string object - but how?

Example:

class test(object):
  pass

a = test()
test.value = 5
a.value
# -> 5
te         


        
相关标签:
1条回答
  • There is a builtin function for this:

    setattr(test, attr_name, 10)
    

    Reference: http://docs.python.org/library/functions.html#setattr

    Example:

    >>> class a(object): pass
    >>> a.__dict__['wut'] = 4
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'dictproxy' object does not support item assignment
    >>> setattr(a, 'wut', 7)
    >>> a.wut
    7
    
    0 讨论(0)
提交回复
热议问题