gpt4 book ai didi

python - 如何在数据类中使用 field()?

转载 作者:行者123 更新时间:2023-12-05 01:30:26 32 4
gpt4 key购买 nike

我经常看到这样的代码:

@dataclass
class ClassName:
list_name: list[int] = field(default_factory=list)

但我不明白为什么我需要输入field(default_factory=list)list_name: list[int] 还不够吗?

您能否解释一下何时、为何以及如何在数据类中使用 field()?

最佳答案

正在做:

list_name: list[int]

不同于:

list_name: list[int] = field(default_factory=list)

后者使用了一个default_factory,所以注意:

>>> from dataclasses import dataclass
>>> @dataclass
... class ClassName:
... list_name: list[int]
...
>>> ClassName()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() missing 1 required positional argument: 'list_name'

但是如果你使用默认工厂:

>>> @dataclass
... class ClassName:
... list_name: list[int] = field(default_factory=list)
...
>>> ClassName()
ClassName(list_name=[])

请注意,如果您执行了 list_name: list[int] = [],那么它将重新使用相同的 list 对象实例,几乎肯定不是你想要的。实际上,dataclass 装饰器明确拒绝了这一点:

>>> @dataclass
... class ClassName:
... list_name: list[int] = []
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/Users/juanarrivillaga/opt/miniconda3/envs/py39/lib/python3.9/dataclasses.py", line 1021, in dataclass
return wrap(cls)
File "/Users/juanarrivillaga/opt/miniconda3/envs/py39/lib/python3.9/dataclasses.py", line 1013, in wrap
return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen)
File "/Users/juanarrivillaga/opt/miniconda3/envs/py39/lib/python3.9/dataclasses.py", line 863, in _process_class
cls_fields = [_get_field(cls, name, type)
File "/Users/juanarrivillaga/opt/miniconda3/envs/py39/lib/python3.9/dataclasses.py", line 863, in <listcomp>
cls_fields = [_get_field(cls, name, type)
File "/Users/juanarrivillaga/opt/miniconda3/envs/py39/lib/python3.9/dataclasses.py", line 747, in _get_field
raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'list'> for field list_name is not allowed: use default_factory

通常,当您需要修改各个字段时,您会显式地使用 dataclasses.field

关于python - 如何在数据类中使用 field()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67011025/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com