如何在不注释类型的情况下添加数据类字段?

2024-10-02 02:36:44 发布

您现在位置:Python中文网/ 问答频道 /正文

当dataclass中有一个字段的类型可以是任何类型时,如何省略注释?在

@dataclass
class Favs:
    fav_number: int = 80085
    fav_duck = object()
    fav_word: str = 'potato'

上面的代码似乎并没有为fav_duck创建字段。它只是使它成为一个普通的老类属性。在

^{pr2}$

Tags: 代码类型numberobjectclassword省略potato
2条回答

dataclass装饰器通过在__annotations__中查找名称来检查类以查找字段。It is the presence of annotation which makes the field,所以,您确实需要一个注释。

但是,您可以使用通用的:

@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上下文中的术语“field”要求属性具有定义的类型注释。

请注意,使用像typing.Any这样的泛型类型注释与具有未注释的属性不同,因为该属性将出现在__annotations__中。

最后,在只提供属性名的情况下,helper函数make_dataclass将自动使用typing.Any作为类型注释,这也在PEP中通过一个例子提到。

相关问题 更多 >

    热门问题