首页 > 解决方案 > 在另一个 NamedTuple 中创建一个 NamedTuple 并将其设置为该 Tuple 中条目的默认值

问题描述

我目前正在编写一个 Python 3.8 程序,它应该最终创建一个 XML 文件。对于这个 XML 文件的内容,我创建了一些 NamedTuples 作为数据类来保存内容,每个条目都有一个默认值(这对于 XML 格式很重要,每个条目都需要一个默认值,并且可能会或可能不会在期间设置运行时),但 XML 文件中的某些模块需要子模块,而这些子模块又需要子模块,依此类推。所以我在第一个 NamedTuple 中创建了更多 NamedTuples,如下所示:

@dataclass
class XMLGenerator(NamedTuple):
    generator_comment: str = 'description of the software which generates this XML file'
    name: str = 'default name'
    type: str = 'logbook'

    @dataclass
    class Manufacturer(NamedTuple):
        manufacturer_name: str = 'Default Co.'
        contact_data: str = 'Address'
    manufacturer: Manufacturer = Manufacturer()
    version: str = '3.14159'

我的问题是,每当我生成一个新的 set tuple 实例时,它都会在行中失败:

manufacturer: Manufacturer = Manufacturer()

File "<string>", line 3, in __init__ AttributeError: can't set attribute

我知道这可能是一些简单的语法错误,但我不知道如何正确地做到这一点。

编辑:如果我这样做和处理数据的方式很愚蠢,而你有更好的方法来做到这一点,也请纠正我,这只是我想到的第一种方法的草图。

标签: pythonpython-3.xnamedtuple

解决方案


推荐阅读