如何通过__dict__分配新的类属性?

时间:2022-06-04 18:11:33

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
test.__dict__['value']
# -> 5

# BUT:
attr_name = 'next_value'

test.__dict__[attr_name] = 10
# -> 'dictproxy' object does not support item assignment

1 个解决方案

#1


64  

There is a builtin function for this:

这有一个内置函数:

setattr(test, attr_name, 10)

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

参考: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

#1


64  

There is a builtin function for this:

这有一个内置函数:

setattr(test, attr_name, 10)

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

参考: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