Python 类型注解错误:'type' object is not subscriptable

以下代码在定义变量 my_listmy_tuple 时使用类型注解,并尝试指定列表和元组中元素的类型,但会报以下错误:

var_1: int = 10
var_2: str = 'hello'

class Student:
    pass

stu: Student = Student()

my_list: list = [1, 2, 3]
my_tuple: tuple = (1, 2, 3)

my_tuple: tuple[int, str, bool] = (1, 'hello', True)
my_list: list[int] = [1, 2, 3]
Traceback (most recent call last):
  File "E:\progarm\python\my_python_project\exercise.py", line 13, in <module>
    my_list: list[int] = [1, 2, 3]
TypeError: 'type' object is not subscriptable

错误原因:

这个错误的原因是,在 Python 3.8 之前,类型注解只能用于类型提示,不能用于指定列表和元组中元素的类型。因此,当解释器执行到这两行代码时会报错,提示“'type' object is not subscriptable”。

解决方案:

  1. 使用注释形式的类型提示:

在 Python 3.8 之前,可以使用注释形式的类型提示,如下所示:

var_1: int = 10
var_2: str = 'hello'

class Student:
    pass

stu: Student = Student()

my_list = [1, 2, 3]  # 使用注释形式的类型提示
my_tuple = (1, 2, 3)  # 使用注释形式的类型提示

my_tuple: tuple[int, str, bool] = (1, 'hello', True)
my_list: list[int] = [1, 2, 3]
  1. 升级 Python 版本:

从 Python 3.9 开始,支持使用类型注解来指定列表和元组中元素的类型。如果您的 Python 版本低于 3.9,建议升级到 3.9 或更高版本。

希望这篇文章能帮助您解决 Python 类型注解中遇到的问题。

Python 类型注解错误:'type' object is not subscriptable

原文地址: https://www.cveoy.top/t/topic/cxIB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录