型別註記

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

# Trying to create a class can be tricky
walker = Student("Sarah Walker", 319921, 15000)
  • student_id 應該是整數嗎?
  • tuition_balance 該用 float 還是整數?或是字串?
  • 建立 walker 之後,之後在程式裡要怎麼記住它的型別?
Python 物件導向程式設計進階

型別註記

可選用的工具,讓你在程式碼中加入物件的資訊。

  • 更易讀、較好除錯
  • 展現企業級 Python 技能的最佳方式之一
  • 直譯器不會強制執行
  • 內建型別關鍵字、typing 函式庫、自訂類別
# Add type hinting when creating a 
# variable
gpa: float = 3.92
# Add type hinting to a function/method 
# definition
def check_grades(year: str) -> List[int]:
    ...
# Can even use custom classes
students: Dict[str, Student] = {...}
Python 物件導向程式設計進階

使用內建型別關鍵字做型別註記

# Type hinting for declarative logic
name: str = "Frost"  # Before: name = "Frost"
student_id: int = 91031367
tuition_balance: float = 17452.78
# Type hinting for function/method definitions
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
# Use Student and Course to type hint
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 物件導向程式設計進階

一起來練習吧!

Python 物件導向程式設計進階

Preparing Video For Download...