我正在尝试将数据类用于某些东西,并且其中我需要初始化一个空集,但是我在弄清楚如何做到这一点上遇到了麻烦。在使用数据类(仅是常规类)之前,我的工作等效项是self.children = set()
,这对我来说很合适。如何在数据类中获得等价物?
我需要默认对其进行初始化,而不必每次都作为参数传递。
from dataclasses import dataclass, field
@dataclass(unsafe_hash=True)
class Node:
index: int
name: str
children: set = field(default_factory=set, hash=True)
尝试将项目添加到集合时出现错误。添加的项目的类型为Node(上面的类)。
root.children.add(child)
File "<string>", line 2, in __hash__
TypeError: unhashable type: 'set'
答案 0 :(得分:2)
它是:
children: set = field(default_factory=set)
默认的工厂是函数,在初始化返回初始值的字段时将调用该函数。因此,将其传递给set
而不调用它,该函数在调用时会返回一个新集合。您还必须为数据类添加: set
类型的批注,以将其作为字段。