Fullstack Python
Trang chủ / Module 2
🧰 Module 2 / 19 · 4 ngày 📅 Tuần 1-2 ●●○○ Trung bình

Python nâng cao & công cụ: OOP, protocol, descriptor, uv, ruff, mypy

Data model của Python (dunder method), OOP và composition, Protocol và ABC, descriptor và property, SOLID theo kiểu Python; quản lý dự án hiện đại bằng uv và pyproject.toml, lint/format bằng ruff, kiểm tra kiểu bằng mypy/pyright, pre-commit.

OOPProtocolDescriptoruvruffmypy/pyright
📌 Vì sao module này quan trọng

Các framework bạn dùng hằng ngày (Django ORM, SQLAlchemy, Pydantic, FastAPI) được xây trên descriptor, metaclass, dunder method và type hints — hiểu chúng giúp bạn debug và mở rộng framework thay vì đoán. Và một dự án Python chuyên nghiệp năm 2026 bắt đầu bằng công cụ: uv quản lý môi trường/phụ thuộc trong vài giây, ruff thay cả flake8/isort/black, type checker chạy trong CI. Người còn pip install vào Python hệ thống sẽ bị nhận ra ngay khi làm take-home.

🎯 Mục tiêu học tập

  • Hiểu data model: __repr__, __eq__/__hash__, __iter__, __enter__/__exit__, __call__
  • Thiết kế bằng composition, Protocol, ABC; áp dụng SOLID kiểu Python
  • Hiểu descriptor, property, __slots__ và cách ORM dùng chúng
  • Quản lý dự án bằng uv và pyproject.toml, lockfile, nhiều phiên bản Python
  • Thiết lập ruff, mypy/pyright, pre-commit làm chuẩn chất lượng

Data model và OOP kiểu Python

class Money:
    __slots__ = ("amount", "currency")

    def __init__(self, amount: int, currency: str) -> None:
        self.amount, self.currency = amount, currency

    def __repr__(self) -> str:                         # hiển thị khi debug/log
        return f"Money({self.amount!r}, {self.currency!r})"

    def __eq__(self, other: object) -> bool:
        return isinstance(other, Money) and (self.amount, self.currency) == (other.amount, other.currency)

    def __hash__(self) -> int:                         # định nghĩa __eq__ thì phải nghĩ tới __hash__
        return hash((self.amount, self.currency))

    def __lt__(self, other: "Money") -> bool: ...
  • Python ưu tiên duck typing và composition; kế thừa sâu hiếm khi là lựa chọn tốt.
  • Protocol (structural typing) cho interface nhẹ; abc.ABC khi muốn ép lớp con cài đặt method.
  • Module là singleton tự nhiên — không cần pattern Singleton kiểu Java.
  • MRO và super() trong đa kế thừa (mixin của Django) — đọc Class.__mro__ khi bối rối.

Descriptor, property và cách ORM hoạt động

class Positive:
    def __set_name__(self, owner, name): self.name = "_" + name
    def __get__(self, obj, objtype=None): return getattr(obj, self.name)
    def __set__(self, obj, value):
        if value <= 0: raise ValueError(f"{self.name[1:]} phải dương")
        setattr(obj, self.name, value)

class Product:
    price = Positive()          # mỗi lần gán product.price = x đều qua __set__
    stock = Positive()

Đây chính là cơ chế đằng sau models.CharField của Django, Mapped[...] của SQLAlchemy và field của Pydantic: thuộc tính class là descriptor kiểm soát việc đọc/ghi. @property là descriptor dựng sẵn. Metaclass (__init_subclass__ là cách nhẹ hơn) cho phép framework "đăng ký" model khi class được định nghĩa.

uv và pyproject.toml

uv init taskflow && cd taskflow
uv python pin 3.13
uv add fastapi "sqlalchemy[asyncio]" asyncpg pydantic-settings
uv add --dev pytest pytest-asyncio ruff mypy
uv run pytest                 # chạy trong môi trường ảo của dự án, tự đồng bộ theo uv.lock
uv sync --frozen              # CI/Docker: cài đúng theo lockfile

# pyproject.toml
[project]
name = "taskflow"
requires-python = ">=3.13"
dependencies = ["fastapi>=0.115", "sqlalchemy[asyncio]>=2.0", "asyncpg>=0.30", "pydantic-settings>=2.6"]

[tool.ruff]
line-length = 100
[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP", "SIM", "S", "ASYNC", "RUF"]   # S = bandit (bảo mật), ASYNC = lỗi async

[tool.mypy]
strict = true
plugins = ["pydantic.mypy"]
  • Commit uv.lock; không bao giờ cài vào Python hệ thống. Poetry/pip-tools vẫn gặp trong dự án cũ.
  • Cấu trúc src/ layout tránh import nhầm code chưa cài.
  • pre-commit chạy ruff format + ruff check + mypy trước mỗi commit; CI chạy lại cùng lệnh.

SOLID và pattern theo kiểu Python

PatternCách viết Pythonic
StrategyTruyền hàm hoặc object thoả Protocol — không cần hệ phân cấp class
FactoryClassmethod Money.from_string(), dict ánh xạ tên → class
RepositoryClass bọc truy vấn SQLAlchemy, phụ thuộc vào session được inject
Decorator patternDecorator hàm, hoặc class bọc (cache, retry, log)
Dependency InjectionTham số constructor/hàm + Depends của FastAPI; hiếm khi cần container
ObserverSignal (Django), event bus đơn giản, hàng đợi

🏋️ Bài tập thực hành

Khung dự án chuẩn cho cả khoá

(1) Tạo dự án taskflow bằng uv, src layout, Python 3.13. (2) Cấu hình ruff (lint + format), mypy strict (hoặc pyright strict), pre-commit, pytest. (3) Viết package taskflow.domain với value object có dunder đầy đủ, một descriptor validate, Protocol PaymentGateway và hai cài đặt giả lập. (4) GitHub Actions chạy uv sync --frozen, ruff, mypy, pytest trên Python 3.13 và 3.14. (5) Cố ý tạo lỗi kiểu và lỗi bảo mật (eval), chứng minh CI chặn được.

📚 Tài nguyên học tập

✅ Tự đánh giá hoàn thành

  • Giải thích được __eq__/__hash__ và descriptor bằng ví dụ ORM
  • Dự án dùng uv + pyproject + lockfile, không cài vào Python hệ thống
  • ruff, mypy/pyright strict, pre-commit, CI hoạt động
  • Dùng Protocol và composition thay kế thừa sâu