如何在不注释类型的情况下添加数据类字段? [英] How to add a dataclass field without annotating the type?

查看:95
本文介绍了如何在不注释类型的情况下添加数据类字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当数据类中存在一个字段,其类型可以是任何类型时,如何省略注释?

When there is a field in a dataclass for which the type can be anything, how can you omit the annotation?

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

似乎上面的代码实际上并未为fav_duck创建一个字段.只是使它成为普通的旧类属性.

It seems the code above doesn't actually create a field for fav_duck. It just makes that a plain old class attribute.

>>> Favs()
Favs(fav_number=80085, fav_word='potato')
>>> print(*Favs.__dataclass_fields__)
fav_number fav_word
>>> Favs.fav_duck
<object at 0x7fffea519850>

推荐答案

数据类装饰器通过在__annotations__中查找名称来检查该类以查找字段. 注释的存在使该字段成为,所以,您确实需要注释.

The dataclass decorator examines the class to find fields, by looking for names in __annotations__. It is the presence of annotation which makes the field, so, you do need an annotation.

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

You can, however, use a generic one:

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

这篇关于如何在不注释类型的情况下添加数据类字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆