Day 6:Object-Oriented Programming (OOP), `@dataclass` & Git/GitHub Version Control
Battle-tested daily lesson note • 100% runnable code, interview Q&A, test suite & interactive quiz
Week 1 — Day 6: Object-Oriented Programming (OOP), @dataclass & Git/GitHub Version Control
Mentor's Note (10+ YOE Staff AI Engineer POV): Why do we combine Object-Oriented Programming (OOP) and Git/GitHub on Day 6?
- Why AI Engineers Need OOP: Every major AI library you will ever touch—
PyTorch(class MyModel(nn.Module):),Pydantic(class RunbookResponse(BaseModel):),FastAPI,LangGraph, andOpenAI—is built on Classes, Objects, Inheritance, and Dataclasses. If you don't understandclass,__init__,self,@dataclass, and Inheritance vs Composition, PyTorch and Pydantic look like magic spells instead of simple Python code!- Why AI Engineers Need Git: In production, you never save files as
copilot_final_v2_REAL_FINAL.py. You use Git commits and branches so you can track every prompt change, run automated CI evaluations on Pull Requests, and revert broken code in 1 second.
Part 1: Object-Oriented Programming (OOP) From Zero
1.1 What is a Class vs an Object (Instance)?
- A Class (
class) is the Blueprint / Cookie Cutter (defines what data attributes and action methods something has). - An Object (Instance) is the Actual House / Cookie built from that blueprint in RAM!
class LLMConfig:
"""Blueprint for holding an LLM model's configuration."""
# 1. `__init__` is the Constructor method called automatically when creating an object:
def __init__(
self, model_name: str, temperature: float = 0.0, max_tokens: int = 1024
) -> None:
# `self` refers to THIS specific object instance in RAM!
self.model_name = model_name
self.temperature = temperature
self.max_tokens = max_tokens
# 2. A regular instance method (always takes `self` as first parameter):
def is_deterministic(self) -> bool:
return self.temperature == 0.0
# 3. `__repr__` controls how the object prints in terminal/debugger logs:
def __repr__(self) -> str:
return f"LLMConfig(model_name={self.model_name!r}, temperature={self.temperature})"
# Creating two separate Object Instances from the same Class blueprint:
gemini_cfg = LLMConfig("gemini-2.5-flash", temperature=0.0)
creative_cfg = LLMConfig("gpt-4o-mini", temperature=0.8)
Part 2: Modern Python @dataclass (Zero Boilerplate!)
Writing self.a = a, self.b = b, and __repr__ by hand for data containers gets repetitive. Python 3.7+ introduced @dataclass, which automatically writes __init__, __repr__, and __eq__ (== comparison) for you!
from dataclasses import dataclass, field
@dataclass(
frozen=False
) # Set frozen=True if you want the object to be immutable!
class RunbookSection:
source_file: str
section_header: str
content: str
keywords: set[str] = field(default_factory=set)
@property
def citation_id(self) -> str:
"""Computed property accessed like an attribute (`section.citation_id`)."""
clean_header = self.section_header.lstrip("#").strip()
return f"[{self.source_file}#{clean_header}]"
[!TIP] Notice
field(default_factory=set)! Remember Day 4's Mutable Default Argument trap?@dataclassis so smart that if you try to writekeywords: set[str] = set(), Python immediately refuses withValueError: mutable default <class 'set'> is not allowed: use default_factory! Usingfield(default_factory=set)callsset()freshly for every new instance!
Part 3: Inheritance ("IS-A") vs Composition ("HAS-A")
- Inheritance (
class Child(Parent):— "IS-A" relationship):- Used when a specialized class is a type of base class.
- Example in PyTorch:
class TransformerBlock(nn.Module):(Your block is a neural network module). - Example in Pydantic:
class RunbookResponse(BaseModel):(Your schema is a Pydantic model).
- Composition ("HAS-A" relationship — Preferred in System Architecture!):
- Instead of tangled 5-level inheritance trees, build small focused classes and compose them together:
- A
RunbookDocumenthas alist[RunbookSection]. - A
RAGPipelinehas aVectorRetriever, aCrossEncoderReranker, and anLLMGenerator.
Part 4: Git & GitHub Version Control From Zero to Pro
4.1 How Git Works Visually (The 4 Areas)
[1. Working Directory] ──(git add)──> [2. Staging Area] ──(git commit)──> [3. Local .git Repo] ──(git push)──> [4. Remote GitHub]
(Your edited files) (Ready for snapshot) (Permanent history) (Cloud portfolio)
4.2 The Essential Git Commands Every Engineer Uses Daily
| Step | Command | What It Does |
|---|---|---|
| 1. Initialize a repo | git init | Creates a hidden .git/ folder to start tracking changes in the current project. |
| 2. Check status | git status | Shows which files are untracked, modified, or staged for commit (and confirms .env is ignored!). |
| 3. Stage files | git add . or git add file.py | Moves changes into the Staging Area ready to be snapshotted. |
| 4. Save a snapshot | git commit -m "feat: add week 1 runbook parser" | Permanently records a snapshot with a descriptive message and unique SHA hash. |
| 5. View commit history | git log --oneline -n 5 | Shows the last 5 commits with their short IDs and messages. |
| 6. See exact line diffs | git diff | Shows the exact + (added) and - (removed) lines before you stage them. |
| 7. Create & switch branch | git switch -c feat/rag-engine | Creates an isolated branch so you can build new features without breaking main. |
8. Merge branch into main | git switch main then git merge feat/rag-engine | Combines your finished feature branch back into main. |
| 9. Push to GitHub | git push -u origin main | Uploads your local commits to your GitHub portfolio repository. |
Part 5: Hands-On Lab — Object-Oriented Runbook Domain Models (models.py)
Check out src/models.py (in Tab 2: Codes — click Run in Browser to execute) where we build the object-oriented data models (RunbookSection, RunbookDocument, SearchResult) using @dataclass, @property, class inheritance (BaseDocument), and composition!
Run Day 6 Code & Tests:
python week01_computer_terminal_git_python_basics/day06_oop_classes_and_git_github/src/models.py
python -m unittest discover -s week01_computer_terminal_git_python_basics/day06_oop_classes_and_git_github/tests -v