2024-10-02 02:36:44 发布
网友
当dataclass中有一个字段的类型可以是任何类型时,如何省略注释?在
@dataclass class Favs: fav_number: int = 80085 fav_duck = object() fav_word: str = 'potato'
上面的代码似乎并没有为fav_duck创建字段。它只是使它成为一个普通的老类属性。在
fav_duck
dataclass装饰器通过在__annotations__中查找名称来检查类以查找字段。It is the presence of annotation which makes the field,所以,您确实需要一个注释。
__annotations__
但是,您可以使用通用的:
@dataclass class Favs: fav_number: int = 80085 fav_duck: 'typing.Any' = object() fav_word: str = 'potato'
根据定义数据类含义的PEP 557
The dataclass decorator examines the class to find fields. A field is defined as any variable identified in __annotations__. That is, a variable that has a type annotation.
dataclass
也就是说,这个问题的前提条件(例如“如何将dataclass与没有类型注释的字段一起使用”)必须被拒绝。dataclass上下文中的术语“field”要求属性具有定义的类型注释。
请注意,使用像typing.Any这样的泛型类型注释与具有未注释的属性不同,因为该属性将出现在__annotations__中。
typing.Any
最后,在只提供属性名的情况下,helper函数make_dataclass将自动使用typing.Any作为类型注释,这也在PEP中通过一个例子提到。
make_dataclass
dataclass装饰器通过在
__annotations__
中查找名称来检查类以查找字段。It is the presence of annotation which makes the field,所以,您确实需要一个注释。但是,您可以使用通用的:
根据定义数据类含义的PEP 557
也就是说,这个问题的前提条件(例如“如何将
dataclass
与没有类型注释的字段一起使用”)必须被拒绝。dataclass
上下文中的术语“field”要求属性具有定义的类型注释。请注意,使用像
typing.Any
这样的泛型类型注释与具有未注释的属性不同,因为该属性将出现在__annotations__
中。最后,在只提供属性名的情况下,helper函数
make_dataclass
将自动使用typing.Any
作为类型注释,这也在PEP中通过一个例子提到。相关问题 更多 >
编程相关推荐