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

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

问题描述

当数据类中有一个字段的类型可以是任何类型时,如何省略注解?

@dataclass班级最爱:收藏编号:int = 80085fav_duck = object()fav_word: str = '土豆'

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

<预><代码>>>>收藏夹()收藏夹(fav_number=80085, fav_word='土豆')>>>打印(*收藏.__dataclass_fields__)fav_number fav_word>>>收藏夹.fav_duck<对象在 0x7fffea519850>

解决方案

数据类装饰器通过在 __annotations__ 中查找名称来检查类以查找字段.正是注解的存在使得字段,所以,你做需要注释.

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

@dataclass班级最爱:收藏号码:int = 80085fav_duck: 'typing.Any' = object()fav_word: str = '土豆'

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'

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>

解决方案

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天全站免登陆