类型提示

Python 面向对象编程进阶

Jake Roach

Data Engineer

没有类型提示的代码

class Student:
    def __init__(self, name, student_id, tuition_balance):
        self.name = name
        self.student_id = student_id
        self.tuition_balance = tuition_balance

# 创建类实例可能不容易
walker = Student("Sarah Walker", 319921, 15000)
  • student_id 应该是整数吗?
  • tuition_balance 应为浮点数还是整数?也可能是字符串?
  • 创建 walker 后,稍后在代码中如何记住它的类型?
Python 面向对象编程进阶

类型提示

可选工具,可在代码中附加对象信息

  • 更易读、易排错
  • 展示企业级 Python 能力的最佳方式之一
  • 解释器不强制执行
  • 内置类型关键字、typing 库、自定义类
# 在创建变量时添加类型提示
gpa: float = 3.92

# 在函数/方法定义中添加类型提示 def check_grades(year: str) -> List[int]: ...
# 也可使用自定义类 students: Dict[str, Student] = {...}
Python 面向对象编程进阶

使用内置类型关键字进行类型提示

# 声明式逻辑的类型提示
name: str = "Frost"  # 之前:name = "Frost"
student_id: int = 91031367
tuition_balance: float = 17452.78
# 函数/方法定义的类型提示
def get_schedule(semester: str) -> dict:
    ...
  • 语法 variable: type
  • 用于声明、函数/方法签名
  • def .... () -> type: 指定返回类型
Python 面向对象编程进阶

typing 库

typing 是用于提供更多类型提示工具的库

  • ListDictTuple
  • 可提示顶层对象及其元素
from typing import List, Dict

student_names: List[str] = ["Morgan", "Chuck", "Anna"]
student_gpas: Dict[str, float] = {
    "Casey": 3.71,
    "Sarah": 4.0
}
  • AnySetIteratorCallable
Python 面向对象编程进阶

使用自定义类进行类型提示

class Student:
    def __init__(self, name: str, student_id: int, tuition_balance: float) -> None:
        self.name: str = name
        self.student_id: int = student_id
        self.tuition_balance: float = tuition_balance

    def get_course(self, course_id: str) -> Course:
        ...
        return course
# 使用 Student 和 Course 做类型提示
walker: Student = Student("Sarah Walker", 319921, 15000)
data_science: Course = walker.get_course("TDM-20100")
Python 面向对象编程进阶

检查对象类型

# walker: Student = Student("Sarah Walker", 319921, 15000)
print(type(walker))
<class '__main__.Student'>
# data_science: Course = walker.get_course("TDM-20100")
print(type(data_science))
<class '__main__.Course'>
Python 面向对象编程进阶

Passons à la pratique !

Python 面向对象编程进阶

Preparing Video For Download...