【python】类型注解
参考
【为什么越来越多Python项目都在写类型注解?】 https://www.bilibili.com/video/BV1sW81zbEkD/?share_source=copy_web&vd_source=9332b8fc5ea8d349a54c3989f6189fd3
代码示例
使用变量 : 类型名 来注解。
"""
python类型注解
"""
from datetime import datetime
from typing import List, Dict, Tuple, Literal
from __future__ import annotations# 类型注解不会强制检查
a: int = 'str'
print(a)class Student:# 各种类型的注解示例,在pycharm上按下alt+enter快速生成类型提示模板# datetime是导入的类型,3.8版本不允许 datetime | str 的格式# 用Literal表示某个属性只是某些值def __init__(self, name: str, birthdate: datetime, courses: List[str], scores: Dict[str, float],sex: Literal['male', 'female'],location: Tuple[float, float]):self.birthdate = birthdateself.name = nameself.courses = coursesself.scores = scoresself.location = locationself.sex = sex# 解决前向引用,出现还没定义完成的类型,from __future__ import annotations,延迟解析def follow(self, other_stu: Student): # 也可使用"Student"pass# 箭头后表示期望的返回类型
def create_stu(name, birthdate, courses, score, location) -> Student:return Student(name, birthdate, courses, score, location)s = Student(name='luo', courses=['chinese', 'math'], scores={'chinese': 78, 'math': 76}, location=(110, 200),birthdate=datetime(1999, 11, 1), sex='male')