gpt4 book ai didi

python - 将默认列表参数传递给数据类

转载 作者:太空狗 更新时间:2023-10-29 22:06:16 25 4
gpt4 key购买 nike

我想在我的类里面传递默认参数,但不知何故我遇到了问题:

from dataclasses import dataclass, field
from typing import List

@dataclass
class Pizza():
ingredients: List = field(default_factory=['dow', 'tomatoes'])
meat: str = field(default='chicken')

def __repr__(self):
return 'preparing_following_pizza {} {}'.format(self.ingredients, self.meat)

如果我现在尝试实例化 Pizza,我会收到以下错误:

>>> my_order = Pizza()
Traceback (most recent call last):
File "pizza.py", line 13, in <module>
Pizza()
File "<string>", line 2, in __init__
TypeError: 'list' object is not callable

我做错了什么?

最佳答案

来自 the dataclasses.field docs :

The parameters to field() are:

  • default_factory: If provided, it must be a zero-argument callable thatwill be called when a default value is needed for this field. Amongother purposes, this can be used to specify fields with mutabledefault values, as discussed below. It is an error to specify bothdefault and default_factory.

你的 default_factory 不是一个 0 参数的可调用对象而是一个列表,这就是错误的原因:

from dataclasses import dataclass, field
from typing import List

@dataclass
class Pizza():
ingredients: List = field(default_factory=['dow', 'tomatoes']) # <- wrong!

改为使用 lambda 函数:

@dataclass
class Pizza():
ingredients: List = field(default_factory=lambda: ['dow', 'tomatoes'])

关于python - 将默认列表参数传递给数据类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52063759/

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