Inheritance & encapsulation · Kế thừa & Bao封装
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.)
Xây dựng dựa trên một lớp có sẵn
- Kế thừa cho phép một lớp mới tái sử dụng một lớp đã tồn tại.
- Lớp mới là lớp con (con); lớp gốc là lớp cha (bố mẹ).
- Viết
class Bird(Animal):—Birdsẽ kế thừa tất cả các phương thức củaAnimal. (Trong伪代码 đề thi: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.
Gọi lớp cha bằng super()
- Lớp con có thể thêm các thuộc tính riêng của nó trong
__init__. - Sử dụng
super().__init__(...)để chạy trước__init__của lớp cha. - Điều này tránh việc lặp lại mã thiết lập của lớp cha.
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.
Ghi đè một phương thức
- Một lớp con có thể ghi đè một phương thức: định nghĩa một phương thức với cùng tên.
- Phiên bản của lớp con sẽ được sử dụng thay cho phiên bản của lớp cha.
- Điều này giúp mỗi lớp hành xử theo cách riêng của nó.
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.
Đóng gói (Encapsulation)
- Đóng gói có nghĩa là giữ dữ liệu của đối tượng an toàn bên trong nó.
- Python không có "private" thực sự, nhưng dấu gạch dưới ở đầu (
self._balance) báo hiệu "đừng chạm vào từ bên ngoài". - Mã khác nên sử dụng phương thức để đọc hoặc thay đổi dữ liệu, chứ không tiếp cận trực tiếp.
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.
Đa hình (Polymorphism)
- Đa hình có nghĩa là một tên phương thức, nhưng hành vi khác nhau tùy theo lớp.
- Một vòng lặp có thể gọi
.speak()trên nhiều đối tượng mà không cần biết chính xác loại của chúng. - Mỗi đối tượng phản hồi theo cách riêng của nó.
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).
Lỗi thường gặp
- Một lớp con kế thừa từ lớp cha và có thể thêm hoặc ghi đè các phương thức.
- Giữ dữ liệu riêng tư và truy cập qua phương thức (đóng gói).
Now you try
- Use inheritance, overriding, encapsulation, and calling methods on different objects.
- Press Check answer to test your code.
Bây giờ bạn thử
- Sử dụng kế thừa, ghi đè, đóng gói và gọi phương thức trên các đối tượng khác nhau.
- Nhấn Check answer (Kiểm tra câu trả lời) để thử mã của bạn.
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.) · Lớp Animal đã được định nghĩa. Viết class con Cat(Animal) kế thừa từ nó và thêm phương thức speak(self) trả về "Meow". (Nó vẫn phải có name_is đã kế thừa.)
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
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 đã được định nghĩa (area của nó trả về 0). Viết Square(Shape): __init__(self, side) của nó phải gọi super().__init__("square"), lưu kết quả vào side, và ghi đè area để trả về side * side.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
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. · Lớp Dog và Cat đã được định nghĩa, mỗi lớp có một speak(). Viết speak_all(animals) trả về danh sách kết quả speak() của mỗi con vật, theo thứ tự.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
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. · Viết một class Account mà trong __init__(self) sẽ thiết lập balance private self._balance thành 0. Thêm deposit(self, amount) để cộng vào, và balance(self) để trả về nó. Các đoạn code khác nên sử dụng các method này, không được tiếp cận trực tiếp _balance.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.