【问题标题】:Convert string to property - AttributeError: can't set attribute将字符串转换为属性 - AttributeError:无法设置属性
【发布时间】:2020-11-13 03:40:08
【问题描述】:

我在下面运行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 是不可变的并且属性设置器受到限制。 AttributeError: can't set attribute AttributeError: can't set attribute in python

但是,我需要将大量字符串从配置字典的键转换为结构或类的属性。这些字符串值不固定,因为它们很多。

有没有办法解决这个AttributeError 我的问题?

【问题讨论】:

  • 不能直接编辑原来的 Dictionary 然后再调用 dict2struct() 函数吗?
  • 那么您是否正在寻找一个类似字典的对象,可以让您通过x.key = value 设置键/值对?我很久以前写过其中一个,从那时起我就一直在使用。我只是在谷歌上搜索,并没有发现任何类似的东西不是作为大量东西的一部分出现的。我很惊讶。我想知道其他人是否几乎自己知道其中一种在野外可用。也许我应该发表我的:)
  • @Steve,我的输入是带有字符串键的字典。输出应该是一个结构/类,以便像这样使用:res.fieldx、res.fieldy 等。你能分享一下你的转换代码吗?
  • 啊。找到了。这可能是你想要的吗? - pypi.org/project/attributedict
  • 这听起来像x y problem。你想用它解决什么问题?

标签: python attributeerror setter converters namedtuple


【解决方案1】:

史蒂夫的上述解决方案对我有用。 pypi.org/project/attributedict

【讨论】:

    猜你喜欢
    • 2015-02-08
    • 1970-01-01
    • 2014-08-09
    • 2017-07-17
    • 1970-01-01
    • 2022-10-08
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多