參考
【為什么越來越多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')