Python 类型提示示例:变量、类、列表、元组
这段代码展示了 Python 中使用类型提示来声明变量、类、列表、元组的示例:
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]
代码中没有错误。
- 使用
:符号来指定变量的类型,例如var_1: int表示var_1变量的类型为int。 - 类定义使用
class关键字,例如class Student定义了一个名为Student的类。 - 列表和元组使用
list和tuple类型,例如my_list: list表示my_list变量为一个列表。 - 使用
[]符号来指定列表和元组的元素类型,例如my_tuple: tuple[int, str, bool]表示my_tuple元组包含int、str和bool类型的值。
类型提示可以帮助提高代码的可读性和可维护性,并且可以帮助静态分析工具检测潜在的错误。
原文地址: https://www.cveoy.top/t/topic/cxKN 著作权归作者所有。请勿转载和采集!