【问题标题】:How to specify method return type list length in Python?如何在 Python 中指定方法返回类型列表长度?
【发布时间】:2022-12-19 23:53:11
【问题描述】:

假设我有这样的方法:

def return_list_with_length_2(self) -> list[int]:
    return [0, 1]

有没有办法指定返回列表的长度始终为 2?

【问题讨论】:

  • 使用元组而不是列表是一个选项吗?
  • @KonradRudolph 我想是的,是否可以在那里指定长度?
  • 2 元素列表与可以具有任意长度的列表是不同的类型。 Python 的类型提示目前不支持这种依赖类型。

标签: python return-type


【解决方案1】:

您可以使用元组作为输出:

def return_list_with_length_2(self) -> tuple[int, int]:
    return (0, 1)

【讨论】:

  • tuple[int] 表示一个 1 元素元组,其 1 元素是一个 int。
猜你喜欢
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多