如果我在编译时不知道属性名是什么,如何设置Python类的属性。?

2024-09-22 14:31:43 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我在编译时不知道属性名是什么(它是通过重定向从文件中读取的),如何设置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()

是否有更好的父类可以继承


Tags: tonameselfsupportread属性objectnot