在namedtuple中输入提示 [英] Type hints in namedtuple

查看:130
本文介绍了在namedtuple中输入提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

from collections import namedtuple
point = namedtuple("Point", ("x:int", "y:int"))

上面的代码只是演示我要实现的目标的一种方法. 我想用类型提示使namedtuple.

The Code above is just a way to demonstrate as to what I am trying to achieve. I would like to make namedtuple with type hints.

您知道如何以一种优雅的方式达到预期效果吗?

Do you know any elegant way how to achieve result as intended?

推荐答案

类型为3.6的命名元组的首选语法为

The prefered Syntax for a typed named tuple since 3.6 is

from typing import NamedTuple

class Point(NamedTuple):
    x: int
    y: int = 1  # Set default value

Point(3)  # -> Point(x=3, y=1)

修改 从Python 3.7开始,请考虑使用 dataclasses (您的IDE可能尚不支持它们进行静态类型检查):

Edit Starting Python 3.7, consider using dataclasses (your IDE may not yet support them for static type checking):

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int = 1  # Set default value

Point(3)  # -> Point(x=3, y=1)

这篇关于在namedtuple中输入提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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