Inheritance & encapsulation
Build on an existing class
- Inheritance lets a new class reuse an existing one.
- The new class is the subclass (child); the original is the superclass (parent).
- Write
class Bird(Animal):—Birdgets all ofAnimal's methods. (In exam pseudocode:CLASS Bird INHERITS Animal.)
Build on an existing class
- Inheritance ทำให้ new class สามารถ reuse一个 existing one
- The new class is the subclass (child); the original is the superclass (parent)
- Write
class Bird(Animal):—Birdgets all ofAnimal's methods. (In exam pseudocode:CLASS Bird INHERITS Animal.)
Call the parent with super()
- A subclass can add its own attributes in
__init__. - Use
super().__init__(...)to run the parent's__init__first. - This avoids repeating the parent's setup code.
Call the parent with super()
- A subclass can add its own attributes in
__init__ - Use
super().__init__(...)to run the parent's__init__first - สิ่งนี้จะหลีกเลี่ยงการเขียนโค้ดตั้งค่าของ parent ซ้ำ
class Animal:
def __init__(self, name):
self.name = name
def describe(self):
return self.name + " is an animal"
class Bird(Animal):
def fly(self):
return self.name + " flies"
b = Bird("Robin")
print(b.describe()) # inherited from Animal
print(b.fly()) # new in Bird
Override a method
- A subclass can override a method: define one with the same name.
- The subclass's version is used instead of the parent's.
- This lets each class behave in its own way.
Override Method (แทนที่เมทโด้)
- Class ลูกสามารถ override เมทโด้ได้: โดยกำหนดเมทโด้ที่มีชื่อเดียวกัน
- จะใช้เวอร์ชันของ class ลูกแทนของ parent
- สิ่งนี้ทำให้แต่ละ class มีพฤติกรรมของตัวเอง
class Animal:
def speak(self):
return "..."
class Cow(Animal):
def speak(self):
return "Moo"
print(Cow().speak())
Encapsulation
- Encapsulation means keeping an object's data safe inside it.
- Python has no real "private", but a leading underscore (
self._balance) signals "do not touch from outside". - Other code should use methods to read or change the data, not reach in directly.
Encapsulation (การห่อหุ้มข้อมูล)
- Encapsulation หมายถึงการเก็บข้อมูลของ object ไว้ภายในอย่างปลอดภัย
- Python ไม่มี "private" จริงๆ แต่มี underscore นำหน้า (
self._balance) เพื่อบ่งบอกว่า "ห้ามเข้าถึงจากภายนอก" - โค้ดอื่นควรใช้ methods ในการอ่านหรือแก้ไขข้อมูล แทนที่จะเข้าไปเข้าถึงโดยตรง
Polymorphism
- Polymorphism means one method name, but different behaviour per class.
- A loop can call
.speak()on many objects without knowing their exact type. - Each object responds in its own way.
Polymorphism (ความหลากหลายของรูปแบบ)
- Polymorphism หมายความว่าเมทโด้ชื่อเดียว แต่มีพฤติกรรมต่างกันตาม class
- Loop สามารถเรียก
.speak()กับหลาย objects ได้โดยไม่ต้องรู้ประเภทที่แน่นอน - แต่ละ object ตอบสนองด้วยวิธีของตัวเอง
class Duck:
def speak(self):
return "Quack"
class Cow:
def speak(self):
return "Moo"
for animal in [Duck(), Cow()]:
print(animal.speak())
Common mistakes
- A subclass inherits from its parent and can add or override methods.
- Keep data private and reach it through methods (encapsulation).
ข้อผิดพลาดที่พบบ่อย
- Class ลูกสืบทอดจาก parent และสามารถเพิ่มหรือ override เมทโด้ได้
- เก็บข้อมูลให้เป็น private และเข้าถึงผ่าน methods (encapsulation)
Now you try
- Use inheritance, overriding, encapsulation, and calling methods on different objects.
- Press Check answer to test your code.
ลองดูเลย
- ใช้ inheritance, overriding, encapsulation และการเรียก methods กับ objects ต่างๆ
- กด Check answer เพื่อทดสอบโค้ดของคุณ
The class Animal is given. Write a subclass Cat(Animal) that inherits from it and adds a method speak(self) returning "Meow". (It should still have the inherited name_is.) · คลาส Animal ถูกกำหนดให้แล้ว เขียน subclass Cat(Animal) ที่ inherit จากมันและเพิ่ม method speak(self) ที่ return "Meow" (ควรมี inherited name_is อยู่ด้วย)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
The class Shape is given (its area returns 0). Write Square(Shape): its __init__(self, side) should call super().__init__("square"), store side, and override area to return side * side. · class Shape ถูกกำหนดให้แล้ว (area ของมัน return 0). เขียน Square(Shape): __init__(self, side) ของมันควรที่จะเรียก super().__init__("square"), เก็บ side, และ override area เพื่อ return side * side
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Classes Dog and Cat are given, each with a speak(). Write speak_all(animals) that returns a list of each animal's speak() result, in order. · Classes Dog และ Cat ถูกกำหนดให้แล้ว, แต่ละตัวมี speak(). เขียน speak_all(animals) ที่ return list ของผลลัพธ์ speak() ของสัตว์แต่ละชนิด, ตามลำดับ
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Write a class Account whose __init__(self) sets a private balance self._balance to 0. Add deposit(self, amount) to add to it, and balance(self) to return it. Other code should use these methods, not touch _balance directly. · เขียนคลาส Account ที่มี __init__(self) ตั้งค่า private balance self._balance เป็น 0 เพิ่ม deposit(self, amount) เพื่อเพิ่มค่า และ balance(self) เพื่อ return ค่านั้น โค้ดอื่นๆ ควรใช้ methods เหล่านี้ ไม่ควรเข้าถึง _balance โดยตรง
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่