Type Hints

Object-Oriented Programming ใน Python ระดับกลาง

Jake Roach

Data Engineer

โค้ดที่ไม่มี type hints

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 ควรเป็น integer หรือเปล่า?
  • tuition_balance ควรเป็น float, integer หรือ string?
  • หลังสร้าง walker แล้ว จะรู้ได้อย่างไรว่าชนิดข้อมูลคืออะไร?
Object-Oriented Programming ใน Python ระดับกลาง

Type hints

เครื่องมือเสริมที่ช่วยระบุข้อมูลเกี่ยวกับออบเจ็กต์ในโค้ด

  • อ่านและแก้ปัญหาได้ง่ายขึ้น
  • หนึ่งในวิธีที่ แสดงทักษะ Python ระดับมืออาชีพได้ดีที่สุด
  • ตัวแปลภาษาไม่บังคับใช้
  • ใช้ได้กับ keyword ในตัว, ไลบรารี 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] = {...}
Object-Oriented Programming ใน Python ระดับกลาง

Type hinting ด้วย keyword ชนิดข้อมูลในตัว

# 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:
    ...
  • ใช้ syntax variable: type
  • ใช้กับการประกาศตัวแปรและ signature ของฟังก์ชัน/เมธอด
  • ใช้ def .... () -> type: เพื่อระบุชนิดของค่าที่ return
Object-Oriented Programming ใน Python ระดับกลาง

ไลบรารี typing

typing คือไลบรารีที่ช่วยเพิ่มเครื่องมือสำหรับ type hinting

  • List, Dict, Tuple
  • ระบุชนิดของออบเจ็กต์หลัก และองค์ประกอบภายใน
from 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, Callable
Object-Oriented Programming ใน Python ระดับกลาง

Type hinting ด้วยคลาสที่กำหนดเอง

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")
Object-Oriented Programming ใน 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'>
Object-Oriented Programming ใน Python ระดับกลาง

มาฝึกกันเถอะ!

Object-Oriented Programming ใน Python ระดับกลาง

Preparing Video For Download...