Classes และ Inheritance
การกำหนด class
หัวข้อที่มีชื่อว่า “การกำหนด class”คีย์เวิร์ด class กำหนด type ใหม่
body ประกอบด้วย methods (ฟังก์ชันที่กำหนดภายใน class) และ class attributes (ที่ instance ทุกตัวใช้ร่วมกัน)
class Dog: species: str = "Canis lupus familiaris" # class attribute
def __init__(self, name: str, age: int) -> None: self.name = name # instance attribute self.age = age # instance attribute
def bark(self) -> str: return f"{self.name} says woof!"self — การอ้างอิง instance
หัวข้อที่มีชื่อว่า “self — การอ้างอิง instance”ทุก instance method รับ instance เป็น argument แรก ซึ่งตามธรรมเนียมตั้งชื่อว่า self
Python ส่งให้อัตโนมัติ คุณไม่ต้องส่งเองเมื่อเรียกใช้:
rex = Dog("Rex", 3)rex.bark() # Python เรียก Dog.bark(rex) ภายใต้ hoodself ไม่ใช่ keyword — คุณตั้งชื่ออื่นได้ — แต่ self เป็น convention สากลใน Python และการเบี่ยงเบนจะทำให้ผู้อ่านและเครื่องมือทุกอย่างสับสน
Instance vs class attributes
หัวข้อที่มีชื่อว่า “Instance vs class attributes”| Instance attribute | Class attribute | |
|---|---|---|
| กำหนดที่ไหน | ภายใน __init__ บน self | โดยตรงใน class body |
| จัดเก็บที่ไหน | บน object แต่ละตัว | บน class เอง |
| การเข้าถึง | obj.attr | ClassName.attr หรือ obj.attr (fallback) |
การแก้ไข class attribute ผ่าน instance จะสร้าง shadow instance attribute และ ไม่ เปลี่ยน class attribute ของ instance อื่น ใช้ class attribute เฉพาะสำหรับ constant หรือ shared state ที่เป็นของ class จริงๆ
Inheritance และ super()
หัวข้อที่มีชื่อว่า “Inheritance และ super()”Subclass สืบทอด methods ทั้งหมดจาก parent
ใช้ super() เพื่อเรียก method ของ parent — ที่พบบ่อยที่สุดคือ super().__init__() เพื่อ initialise state ของ parent
class Animal: def __init__(self, name: str, sound: str) -> None: self.name = name self.sound = sound
def speak(self) -> str: return f"{self.name} says {self.sound}"
class Dog(Animal): def __init__(self, name: str) -> None: super().__init__(name, "woof") # delegate ไปยัง Animal.__init__
def fetch(self, item: str) -> str: return f"{self.name} fetches the {item}!"super() ใช้ได้โดยไม่ต้องส่ง argument ใน Python 3 — ไม่จำเป็นต้องระบุ class หรือ instance อย่างชัดเจน
Demo รันได้จริง
หัวข้อที่มีชื่อว่า “Demo รันได้จริง”class Animal: kingdom: str = "Animalia"
def __init__(self, name: str, sound: str) -> None: self.name = name self.sound = sound
def speak(self) -> str: return f"{self.name} says {self.sound}"
class Dog(Animal): def __init__(self, name: str) -> None: super().__init__(name, "woof")
def fetch(self, item: str) -> str: return f"{self.name} fetches the {item}!"
dog = Dog("Rex")print(dog.speak())print(dog.fetch("ball"))print(Dog.kingdom)print(isinstance(dog, Animal))Loading Python runtime (first run only)…