Lập trình Hướng đối tượng Nâng cao với 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
# Tạo lớp có thể khó
walker = Student("Sarah Walker", 319921, 15000)
student_id có phải là số nguyên không?tuition_balance nên là float hay int? Hay chuỗi?walker, làm sao nhớ kiểu của nó về sau?Công cụ tùy chọn để thêm thông tin về đối tượng vào mã
typing, lớp tùy chỉnh# Thêm gợi ý kiểu khi tạo
# biến
gpa: float = 3.92
# Thêm gợi ý kiểu cho
# hàm/phương thức
def check_grades(year: str) -> List[int]:
...
# Có thể dùng cả lớp tùy chỉnh
students: Dict[str, Student] = {...}
# Gợi ý kiểu cho logic khai báo
name: str = "Frost" # Trước đây: name = "Frost"
student_id: int = 91031367
tuition_balance: float = 17452.78
# Gợi ý kiểu cho định nghĩa hàm/phương thức
def get_schedule(semester: str) -> dict:
...
variable: typedef .... () -> type: để chỉ kiểu trả vềtyping là thư viện cung cấp nhiều công cụ gợi ý kiểu hơn
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
# Dùng Student và Course để gợi ý kiểu
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'>
Lập trình Hướng đối tượng Nâng cao với Python