如果我在编译时不知道属性名是什么(它是通过重定向从文件中读取的),如何设置Python类的属性。我希望self[attrName]=attrvalue
可以工作,但我得到了错误Error 'ManifestReader' object does not support item assignment
下面是一个最小完整可验证示例(MCVE)
class ManifestReader(object):
def Read(self):
try:
### read a file here
### don't know attribute name at compile time
### so need to use self[attrName]=attrValue syntax
attrName="foo"
attrvalue="bar"
self[attrName]=attrvalue
### above line causes the following error
'''
"Error 'ManifestReader' object does not support item assignment"
"Press any key to continue . . ."
'''
except Exception as e:
print("Error " + str(e))
if __name__ == '__main__':
rdr=ManifestReader()
rdr.Read()
是否有更好的父类可以继承
您可以使用
hasattr
、setattr
、getattr
来执行此操作使用
setattr
:相关问题 更多 >
编程相关推荐