ข้ามไปยังเนื้อหา

Classes และ Inheritance

คีย์เวิร์ด 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!"

ทุก instance method รับ instance เป็น argument แรก ซึ่งตามธรรมเนียมตั้งชื่อว่า self Python ส่งให้อัตโนมัติ คุณไม่ต้องส่งเองเมื่อเรียกใช้:

rex = Dog("Rex", 3)
rex.bark() # Python เรียก Dog.bark(rex) ภายใต้ hood

self ไม่ใช่ keyword — คุณตั้งชื่ออื่นได้ — แต่ self เป็น convention สากลใน Python และการเบี่ยงเบนจะทำให้ผู้อ่านและเครื่องมือทุกอย่างสับสน

Instance attributeClass attribute
กำหนดที่ไหนภายใน __init__ บน selfโดยตรงใน class body
จัดเก็บที่ไหนบน object แต่ละตัวบน class เอง
การเข้าถึงobj.attrClassName.attr หรือ obj.attr (fallback)

การแก้ไข class attribute ผ่าน instance จะสร้าง shadow instance attribute และ ไม่ เปลี่ยน class attribute ของ instance อื่น ใช้ class attribute เฉพาะสำหรับ constant หรือ shared state ที่เป็นของ class จริงๆ

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 อย่างชัดเจน

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))
`__init__` ใน Python class มีจุดประสงค์อะไร?
คุณกำหนด `species = 'Canis'` โดยตรงใน class body เป็น attribute ประเภทใด?
ภายใน instance method `self` อ้างถึงอะไร?
`super().__init__(name, sound)` ภายใน subclass ทำอะไร?