python - 键入库中的示例代码导致 TypeError : 'type' object is not subscriptable, 为什么?

标签 python typing

考虑到 typing 的 Python 文档为什么下面的代码不起作用?

>>> Vector = list[float]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'type' object is not subscriptable
在文档中有与我上面提到的相同的示例。 here
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]
我没有发现有关此示例的问题。

最佳答案

使用 [] 的能力类型的运算符,如 list类型提示是在 3.9 中添加的。
https://docs.python.org/3/whatsnew/3.9.html#type-hinting-generics-in-standard-collections
在早期版本中它会产生你描述的错误,你需要导入 List来自 typing 的对象反而。

from typing import List
List[float]

关于python - 键入库中的示例代码导致 TypeError : 'type' object is not subscriptable, 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66154004/

相关文章:

QTableView:如何设置搜索列

python - 如何从 Pandas 数据框中的文本字段中提取数据?

typescript - 如何对键是类且值是这些类的实例的 Map 进行类型提示?

Python 3.5 键入 ABCMeta 未定义 '__getitem__'

java - 我们可以在 Java 中使用 Robot 类插入 Unicode 字符吗?

python - 当键的名称无效时 TypedDict

python - 如何将 Action 绑定(bind)到 python 中的 tkinter TreeView 的标题?

python - 谷歌云端硬盘 : Getting a Suspended users permission Id

python - 为什么我的程序重复打印列表?

python - 如何膨胀gzipped,base64d字符串