【问题标题】:Python typing for a tuple元组的 Python 类型
【发布时间】:2021-02-07 17:22:40
【问题描述】:

我只是想在 python 3.85 中为元组定义类型。但是,documentation 中的两种方法似乎都无法正常工作:

Tuple(float,str)

结果:

Traceback (most recent call last):

  File "<ipython-input-30-7964c1934b1f>", line 1, in <module>
    Tuple(float,str)

  File "C:\Users\kinsm\anaconda3\lib\typing.py", line 727, in __call__
    raise TypeError(f"Type {self._name} cannot be instantiated; "

TypeError: Type Tuple cannot be instantiated; use tuple() instead

对比:

tuple(float,str)

结果:

Traceback (most recent call last):
  File "<ipython-input-29-fea16b9491a0>", line 1, in <module>
    tuple(float,str)
result:
TypeError: tuple expected at most 1 argument, got 2

【问题讨论】:

  • 您的链接明显使用了方括号

标签: python typing


【解决方案1】:

正确的语法是

from typing import Tuple

### ---- Examples ----- ###
Tuple[float, float]
Tuple[float, str]

【讨论】:

    【解决方案2】:
    from typing import Tuple
    
    out = Tuple[float,str]
    print(out)
    
    x: Tuple[int, str, float] = (3, "yes", 7.5)
    print(x)
    

    输出:

    typing.Tuple[float, str]
    (3, 'yes', 7.5)
    

    【讨论】:

    • 你能补充一些解释吗?
    猜你喜欢
    • 1970-01-01
    • 2018-05-12
    • 2012-02-16
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 2012-06-09
    • 2020-06-04
    • 1970-01-01
    相关资源
    最近更新 更多