简体   繁体   English

如何用列表的副本初始化数据类字段?

[英]How to initialize dataclass field with a copy of a list?

I'm parsing text files which have the following line structure:我正在解析具有以下行结构的文本文件:

name_id, width, [others] name_id,宽度,[其他]

After parsing an input, I'm feeding each parsed line into the dataclass :解析输入后,我将每个解析的行输入dataclass

@dataclass(frozen=True, eq=True)
class Node():
    name: str
    rate: int
    other: list[str] = field(compare = False)

In the middle of the code, I'm removing values from other , which results in removing values from original parse output.在代码的中间,我从other中删除了值,这导致从原始解析输出中删除了值。 I don't want that.我不想要那个。 How can I make dataclass to force making a copy of the list?如何使dataclass强制复制列表?

In common class, as I understand, solution would be:据我了解,在普通班级,解决方案是:

self.other = other.copy()

But if doing so, I should rewrite whole init method which breaks the purpose of dataclass .但如果这样做,我应该重写整个init方法,这破坏了dataclass的目的。

So how to initialize dataclass field with a copy of a list?那么如何用列表的副本初始化dataclass字段呢?

I've tried doing this:我试过这样做:

def __post_init__(self):
    setattr(self, 'other', self.other.copy())

Which yield can't assign attribute of frozen instance.哪个 yield 不能分配冻结实例的属性。

IMHO this is a bad idea and looks like breaking "explicit is better than implicit" aphorisms .恕我直言,这是个坏主意,看起来像是打破了“显式优于隐式”的格言 But if you really want to you can hack force it with object.__setattr__ :但是如果你真的想要,你可以用object.__setattr__破解强制它:

@dataclass(frozen=True, eq=True)
class Node:
    name: str
    rate: int
    other: list[str] = field(compare=False)

    def __post_init__(self):
        object.__setattr__(self, 'other', self.other.copy())

Explanation解释

object.__setattr__ is the default python __setatter__ while __setattr__ uses class's __setattr__ method which in the case of dataclass is overridden to ensure that user doesn't change the field of the frozen dataclass (so you skip the check). object.__setattr__是默认的 python __setatter____setattr__使用类的__setattr__方法,在dataclass的情况下被覆盖以确保用户不会更改冻结dataclass的字段(因此您跳过检查)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM