简体   繁体   English

Python数据类设置带有值的默认列表

[英]Python dataclass setting default list with values

Can anyone help me fix this error.谁能帮我解决这个错误。 I just started using dataclass I wanted to put a default value so I can easily call from other function我刚开始使用数据类,我想设置一个默认值,这样我就可以轻松地从其他函数调用

I have this class我有这门课

@dataclass(frozen=True)
class MyClass:
    my_list: list = ["list1", "list2", "list3"]
    my_list2: list = ["list1", "list2", "list3"]

But when i print print(MyClass.my_list) I'm getting this error但是当我打印 print(MyClass.my_list) 我收到这个错误

 raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'list'> for field my_list is not allowed: use default_factory

What it means by mutable default is that the lists provided as defaults will be the same individual objects in each instance of the dataclass. mutable default意味着作为默认值提供的列表将是数据类的每个实例中相同的单个对象。 This would be confusing because mutating the list in an instance by eg appending to it would also append to the list in every other instance.这会令人困惑,因为通过例如附加到它来改变一个实例中的列表也会附加到每个其他实例中的列表。

Instead, it wants you to provide a default_factory function that will make a new list for each instance:相反,它希望您提供一个default_factory函数,该函数将为每个实例创建一个新列表:

from dataclasses import dataclass, field

@dataclass
class MyClass:
    my_list: list = field(default_factory=lambda: ["list1", "list2", "list3"])
    my_list2: list = field(default_factory=lambda: ["list1", "list2", "list3"])

As the first comment notes, it's a bit odd to have a mutable item in a dataclass.正如第一条评论所指出的,在数据​​类中有一个可变项有点奇怪。 If you don't need it to be mutable, a simpler solution is to initialize it as a tuple.如果你不需要它是可变的,一个更简单的解决方案是将它初始化为一个元组。

from dataclasses import dataclass

@dataclass
class MyClass:
    my_list: tuple(str) = ("list1", "list2", "list3")
    my_list2: tuple(str) = ("list1", "list2", "list3")

(For example, you might want a tuple of fieldnames associated with your dataclass for serialization with DictWriter .) (例如,您可能需要一个与您的数据类关联的字段名元组,以便使用DictWriter进行序列化。)

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

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