我想在类里面传递默认参数,
但以某种方式我有问题:

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:



您的default_factory不是可调用的0参数,而是一个列表,这是导致错误的原因:

@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/

10-13 02:52