menu_book LESSON MODE

OOP Ch.7 — Class & Static Methods

calendar_today Đăng 29 May 2026
OOP Ch.7 — Class & Static Methods
school

NOW LEARNING

OOP Ch.7 — Class & Static Methods

🏗️ OOP Series · Lập trình Hướng đối tượng với Python
🔵
Chapter 7 · OOP Series

Class & Static
Methods

Ba loại method trong Python — và bí quyết chọn đúng loại cho từng tình huống!

⚖️

Instance vs Class vs Static Method

👤
Instance
def fn(self, ...)
  • Truy cập object
  • Dùng self bắt buộc
  • Phổ biến nhất
  • Gọi: obj.fn()
🏛️
Class Method
@classmethod fn(cls,...)
  • Truy cập class
  • Dùng cls thay self
  • Factory pattern
  • Gọi: Class.fn()
⚙️
Static Method
@staticmethod fn(...)
  • Không truy cập gì
  • Không có self/cls
  • Tiện ích độc lập
  • Gọi: Class.fn()
🏭

@classmethod — Factory Pattern

Class method thường dùng như "factory" — tạo object theo nhiều cách khác nhau mà không cần thay đổi __init__:

class HocSinh:
    si_so = 0                  ← class attribute (chung cho tất cả)

    def __init__(self, ten, diem):
        self.ten  = ten
        self.diem = diem
        HocSinh.si_so += 1

    @classmethod
    def tu_chuoi(cls, chuoi):      ← factory: tạo từ chuỗi "Nam:8.5"
        ten, diem = chuoi.split(":")
        return cls(ten, float(diem))

    @classmethod
    def lay_si_so(cls):             ← truy cập class attribute
        return f"Sĩ số lớp: {cls.si_so} học sinh"

    def __str__(self):
        return f"{self.ten}: {self.diem}"

# Tạo object thông thường
hs1 = HocSinh("Nam", 8.5)

# Tạo qua factory classmethod
hs2 = HocSinh.tu_chuoi("Lan:9.0")
hs3 = HocSinh.tu_chuoi("Bình:7.5")

print(hs1, hs2, hs3, sep="\n")
print(HocSinh.lay_si_so())
Nam: 8.5
Lan: 9.0
Bình: 7.5
Sĩ số lớp: 3 học sinh
🔑 cls là tham chiếu đến chính class — giống self nhưng cho class thay vì object. Khi class con kế thừa, cls sẽ trỏ đúng đến class con!
⚙️

@staticmethod — Hàm tiện ích trong Class

Static method không cần self hay cls — chỉ là hàm thông thường nhưng đặt trong class vì nó liên quan logic của class đó:

class HocSinh:
    def __init__(self, ten, diem):
        self.ten  = ten
        self.diem = diem

    @staticmethod
    def xep_loai_theo_diem(diem):     ← không cần self hay cls!
        if   diem >= 8:   return "🌟 Giỏi"
        elif diem >= 6.5: return "✅ Khá"
        elif diem >= 5:   return "📝 TB"
        else:             return "❌ Yếu"

    @staticmethod
    def la_diem_hop_le(diem):
        return 0 <= diem <= 10

    def bao_cao(self):
          # Instance method có thể gọi static method!
        loai = HocSinh.xep_loai_theo_diem(self.diem)
        print(f"{self.ten}: {self.diem} — {loai}")

# Gọi static method KHÔNG cần object!
print(HocSinh.xep_loai_theo_diem(7.2))
print(HocSinh.la_diem_hop_le(11))

hs = HocSinh("Nam", 8.5)
hs.bao_cao()
# Gọi qua object cũng được
print(hs.xep_loai_theo_diem(5.5))
✅ Khá
False
Nam: 8.5 — 🌟 Giỏi
📝 TB
🧭

Bộ câu hỏi quyết định loại method

👤
Instance Method
Method cần đọc/ghi dữ liệu của object?
Ví dụ: tinh_tb(), bao_cao(), nap_tien()
🏭
Class Method
Method tạo object theo cách khác nhau, hoặc cần đọc/ghi class attribute?
Ví dụ: from_string(), from_dict(), get_count()
🔧
Static Method
Hàm tiện ích không cần biết object hay class là gì?
Ví dụ: validate_email(), celsius_to_fahrenheit(), is_valid()
🚀 Dự án nhỏ

Class NhietDo với đủ 3 loại method

class NhietDo:
    don_vi_mac_dinh = "C"      ← class attribute

    def __init__(self, gia_tri, don_vi="C"):
        self.gia_tri = gia_tri
        self.don_vi  = don_vi

    def __str__(self):
        return f"{self.gia_tri}°{self.don_vi}"

      # ── INSTANCE METHODS ──
    def sang_celsius(self):
        if self.don_vi == "F":
            return NhietDo(round((self.gia_tri-32)*5/9, 1))
        return NhietDo(self.gia_tri)

      # ── CLASS METHODS (factories) ──
    @classmethod
    def tu_fahrenheit(cls, f):
        return cls(f, "F")

    @classmethod
    def nhiet_do_phong(cls):
        return cls(25)                ← preset temperature

      # ── STATIC METHODS (utilities) ──
    @staticmethod
    def c_to_f(c): return c * 9/5 + 32

    @staticmethod
    def la_sot(nhiet_c): return nhiet_c > 37.5

# Test
t1 = NhietDo(100)
t2 = NhietDo.tu_fahrenheit(98.6)
t3 = NhietDo.nhiet_do_phong()

print(t1, "→ F:", NhietDo.c_to_f(100))
print(t2, "→ C:", t2.sang_celsius())
print(t3)
print("38.5°C là sốt?", NhietDo.la_sot(38.5))
100°C → F: 212.0
98.6°F → C: 37.0°C
25°C
38.5°C là sốt? True

🧩 Kiểm tra nhanh!

Chapter 7 — Class & Static Methods

1️⃣@classmethod dùng tham số đầu là gì?
→ cls (class reference)
2️⃣@staticmethod có gì đặc biệt?
→ Không có self hay cls
3️⃣@classmethod dùng cho mục đích gì phổ biến?
→ Factory — tạo object nhiều cách
4️⃣Gọi static method cần object không?
→ Không — Class.method() là đủ
OOP Series: Chapter 7 / 10
🔵
📐
Tiếp theo · Chapter 8
Abstract Classes & Interfaces
ABC, @abstractmethod — ép buộc class con phải implement đúng interface. Design theo hợp đồng!

NEXT STEP

Tiếp theo nên học gì

route