Python การสืบทอด (Inheritance)
การสืบทอดคือการสร้างคลาสใหม่โดยต่อยอดจากคลาสที่มีอยู่ คลาสลูก (subclass) ได้ attribute และ method ของคลาสแม่ (superclass) มาทั้งหมด แล้วเพิ่มหรือปรับเปลี่ยนเฉพาะส่วนที่ต่าง ช่วยลดโค้ดซ้ำเมื่อมีหลายคลาสที่คล้ายกัน
ตัวอย่างพื้นฐาน
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} กำลังกิน")
def sleep(self):
print(f"{self.name} กำลังนอน")
class Dog(Animal): # Dog สืบทอดจาก Animal
def bark(self):
print(f"{self.name} เห่า: โฮ่ง!")
d = Dog("บ๊อบบี้")
d.eat() # บ๊อบบี้ กำลังกิน ← ได้จาก Animal
d.sleep() # บ๊อบบี้ กำลังนอน ← ได้จาก Animal
d.bark() # บ๊อบบี้ เห่า: โฮ่ง! ← ของ Dog เองDog ไม่ต้องเขียน __init__, eat, sleep ใหม่ ได้มาจาก Animal ฟรี
override: เขียนทับเมท็อดของแม่
ถ้าคลาสลูกนิยามเมท็อดชื่อเดียวกับแม่ เวอร์ชันของลูกจะถูกใช้แทน
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} ส่งเสียง")
class Cat(Animal):
def speak(self): # override
print(f"{self.name} ร้อง: เมี้ยว")
class Cow(Animal):
def speak(self): # override
print(f"{self.name} ร้อง: มอ")
Animal("สัตว์").speak() # สัตว์ ส่งเสียง
Cat("มีมี่").speak() # มีมี่ ร้อง: เมี้ยว
Cow("ด่าง").speak() # ด่าง ร้อง: มอsuper(): เรียกเมท็อดของคลาสแม่
บ่อยครั้งเราไม่ได้อยาก “แทนที่” เมท็อดแม่ทั้งหมด แต่อยาก “ต่อยอด” จากมัน ใช้ super() เรียกเวอร์ชันของแม่
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def describe(self):
return f"{self.name} เงินเดือน {self.salary}"
class Manager(Employee):
def __init__(self, name, salary, team_size):
super().__init__(name, salary) # ให้แม่ตั้ง name, salary
self.team_size = team_size # แล้วเพิ่มของตัวเอง
def describe(self):
base = super().describe() # เอาข้อความจากแม่
return f"{base} ดูแลทีม {self.team_size} คน"
m = Manager("สมชาย", 80000, 5)
print(m.describe())
# สมชาย เงินเดือน 80000 ดูแลทีม 5 คนsuper().__init__(...) ใน __init__ ของลูกเป็นรูปแบบที่เจอบ่อยมาก — ให้แม่จัดการส่วนที่แม่รับผิดชอบ ลูกค่อยเพิ่มส่วนของตัวเอง
isinstance และ issubclass
d = Dog("บ๊อบบี้")
print(isinstance(d, Dog)) # True
print(isinstance(d, Animal)) # True — Dog เป็น Animal ด้วย
print(isinstance(d, Cat)) # False
print(issubclass(Dog, Animal)) # Trueisinstance(obj, Class) ใช้เช็คชนิดของอ็อบเจกต์ นับรวมคลาสแม่ด้วย
สืบทอดหลายชั้น
class Vehicle:
def __init__(self, brand):
self.brand = brand
class Car(Vehicle):
def __init__(self, brand, doors):
super().__init__(brand)
self.doors = doors
class SportsCar(Car):
def __init__(self, brand, doors, top_speed):
super().__init__(brand, doors)
self.top_speed = top_speed
sc = SportsCar("Toyota", 2, 250)
print(sc.brand, sc.doors, sc.top_speed) # Toyota 2 250เมื่อไหร่ควรใช้สืบทอด
ใช้เมื่อความสัมพันธ์เป็นแบบ “เป็นชนิดหนึ่งของ” (is-a)
Dogเป็นชนิดหนึ่งของAnimal✓Managerเป็นชนิดหนึ่งของEmployee✓
ถ้าความสัมพันธ์เป็นแบบ “มี” (has-a) ให้เก็บเป็น attribute แทน อย่าสืบทอด
CarมีEngine— ควรเป็นself.engine = Engine()ไม่ใช่class Car(Engine)
อย่าสืบทอดลึกหลายชั้นเกินจำเป็น เพราะไล่ตามโค้ดยาก ปัจจุบันหลายคนแนะนำให้ใช้ composition (has-a) เป็นหลัก และใช้ inheritance เท่าที่เหมาะ
ตัวอย่างรวม: รูปทรงเรขาคณิต
class Shape:
def area(self):
raise NotImplementedError("คลาสลูกต้องนิยาม area()")
def describe(self):
return f"{self.__class__.__name__} พื้นที่ {self.area():.2f}"
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
shapes = [Rectangle(4, 5), Circle(3), Rectangle(2, 2)]
for s in shapes:
print(s.describe())ผลลัพธ์:
Rectangle พื้นที่ 20.00
Circle พื้นที่ 28.27
Rectangle พื้นที่ 4.00Shape เป็นคลาสฐานที่บังคับให้ลูกทุกตัวมี area() (ผ่านการ raise NotImplementedError)
เช็คความเข้าใจก่อนข้ามบท
- อธิบายได้ว่า subclass สืบทอด attribute/method จาก superclass อย่างไร
- ใช้ override และ
super()ในตัวอย่างง่าย ๆ ได้ - บอกได้ว่าเมื่อไหร่ควรใช้ inheritance และเมื่อไหร่แค่มี object อีกตัวเป็น attribute ก็พอ
สรุป
- คลาสลูก
class B(A):ได้ทุก attribute/method ของAมาใช้ - นิยามเมท็อดชื่อเดียวกับแม่ = override (เขียนทับ)
super().__init__(...)/super().method()เรียกเวอร์ชันของแม่ เพื่อต่อยอด- ใช้สืบทอดเมื่อเป็น “is-a” ถ้าเป็น “has-a” ให้เก็บเป็น attribute
บทถัดไปว่าด้วย Polymorphism และ method overriding