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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/432786/
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:05:32  来源:igfitidea点击:

How to assign a new class attribute via __dict__?

pythonoopclassattributes

提问by Philipp der Rautenberg

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

回答by gak

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