Convert string to property - AttributeError: can't set attribute
Convert string to property - AttributeError: can't set attribute
我是 运行 python 下面的代码:
def dict2struct(d):
res = namedtuple("config", d.keys())(*d.values())
return res
cfg = {'fieldx': 'Allan', "fieldy": 45, 'fieldt': {'head': False, 'number': 2}}
res = dict2struct(cfg)
print(res)
res.fieldx = "Jack"
并得到错误:
config(fieldx='Allan', fieldy=45, fieldt={'head': False, 'number': 2})
Traceback (most recent call last):
File "*****\Testings\test_x.py", line 97, in <module>
res.fieldx = "Jack"
AttributeError: can't set attribute
我已经阅读了下面的问题,并了解到这是因为 namedtuples
是不可变的,而 属性 setter 被限制了。
AttributeError: can't set attribute
AttributeError: can't set attribute in python
但是,我需要将大量字符串从配置字典的键转换为结构或 class 的属性。这些字符串值不固定,因为它们很多。
有没有办法解决这个 AttributeError
我的问题?
史蒂夫的上述解决方案对我有用。
pypi.org/project/attributedict
我是 运行 python 下面的代码:
def dict2struct(d):
res = namedtuple("config", d.keys())(*d.values())
return res
cfg = {'fieldx': 'Allan', "fieldy": 45, 'fieldt': {'head': False, 'number': 2}}
res = dict2struct(cfg)
print(res)
res.fieldx = "Jack"
并得到错误:
config(fieldx='Allan', fieldy=45, fieldt={'head': False, 'number': 2})
Traceback (most recent call last):
File "*****\Testings\test_x.py", line 97, in <module>
res.fieldx = "Jack"
AttributeError: can't set attribute
我已经阅读了下面的问题,并了解到这是因为 namedtuples
是不可变的,而 属性 setter 被限制了。
AttributeError: can't set attribute
AttributeError: can't set attribute in python
但是,我需要将大量字符串从配置字典的键转换为结构或 class 的属性。这些字符串值不固定,因为它们很多。
有没有办法解决这个 AttributeError
我的问题?
史蒂夫的上述解决方案对我有用。 pypi.org/project/attributedict