# type: 是 Python 3.5 引入的一种类型注释语法,用于在代码中指定变量、函数、方法等对象的类型信息,以便 IDE 和类型检查工具等工具能够更好地理解和分析代码。具体来说,# type: 后面可以跟一个类型注释,用于指定对象的类型,例如:
x = 1 # type: int
y = 'hello' # type: str
在这个例子中,我们使用 # type: 将变量 x 的类型指定为 int,将变量 y 的类型指定为 str。
需要注意的是,# type: 并不会改变变量的实际类型,它只是提供了类型信息,供 IDE 和类型检查工具等工具使用。如下所示

在代码中使用 # type: 时,需要确保指定的类型信息与变量的实际类型一致,否则可能会导致类型检查错误或运行时错误。
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def introduce(self):
print(f"Hi, my name is {self.name}, I'm {self.age} years old, and I'm {self.gender}.")
person = 'hello' # type: Person
person.age # AttributeError: 'str' object has no attribute 'age'
另外,需要注意的是,# type: 是一种注释语法,因此在 Python 解释器中运行代码时,它会被忽略。只有在使用支持类型注释的 IDE 或类型检查工具等工具时,才会被解析和使用。



















