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 后,稍后在代码中如何记住它的类型?可选工具,可在代码中附加对象信息
typing 库、自定义类# 在创建变量时添加类型提示 gpa: float = 3.92# 在函数/方法定义中添加类型提示 def check_grades(year: str) -> List[int]: ...# 也可使用自定义类 students: Dict[str, Student] = {...}
# 声明式逻辑的类型提示
name: str = "Frost" # 之前:name = "Frost"
student_id: int = 91031367
tuition_balance: float = 17452.78
# 函数/方法定义的类型提示
def get_schedule(semester: str) -> dict:
...
variable: typedef .... () -> type: 指定返回类型typing 是用于提供更多类型提示工具的库
List、Dict、Tuplefrom typing import List, Dict
student_names: List[str] = ["Morgan", "Chuck", "Anna"]
student_gpas: Dict[str, float] = {
"Casey": 3.71,
"Sarah": 4.0
}
Any、Set、Iterator、Callableclass 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")
# 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 面向对象编程进阶