Lập trình hướng đối tượng (OOP) trong Python: từ Cơ bản đến thực hành

OOP là gì?

Lập trình hướng đối tượng (OOP) tổ chức code xung quanh các đối tượng thay vì hàm và logic thuần túy.

Class và Object

class SinhVien:
    def __init__(self, ho_ten, ma_sv, diem_tb):
        self.ho_ten = ho_ten
        self.ma_sv = ma_sv
        self.diem_tb = diem_tb

    def xep_loai(self):
        if self.diem_tb >= 8.5:
            return "Giỏi"
        elif self.diem_tb >= 7.0:
            return "Khá"
        return "Trung bình"

    def __str__(self):
        return f"{self.ho_ten} ({self.ma_sv}) - {self.xep_loai()}"

sv1 = SinhVien("Nguyễn Văn A", "SV001", 8.7)
print(sv1)  # Nguyễn Văn A (SV001) - Giỏi

Kế thừa (Inheritance)

class SinhVienIT(SinhVien):
    def __init__(self, ho_ten, ma_sv, diem_tb, ngon_ngu):
        super().__init__(ho_ten, ma_sv, diem_tb)
        self.ngon_ngu = ngon_ngu

    def gioi_thieu(self):
        return f"{self.ho_ten} chuyên về {self.ngon_ngu}"

Các nguyên tắc OOP

  • Encapsulation: Đóng gói dữ liệu
  • Inheritance: Kế thừa và tái sử dụng code
  • Polymorphism: Đa hình
  • Abstraction: Trừu tượng hóa
Chia sẻ bài viết: