Object-Oriented Programming (OOP)

Object-oriented programming organizes data and behavior into objects, managing state through encapsulation, interfaces, and collaboration while ensuring different implementations honor shared behavioral contracts.

One-Sentence Definition

Object-oriented programming organizes data and behavior into objects, managing state through encapsulation, interfaces, and collaboration while allowing different implementations to honor the same behavioral contract.

Why It Matters

  • Managing complex state: A database connection, a chat session, or a neural network layer each carries "its own state + its own operations," making objects a natural representation.
  • The backbone of mainstream frameworks: Django Models, PyTorch's nn.Module, and scikit-learn's fit/predict estimators are all built around OOP conventions.
  • Foundation for Design Patterns and SOLID: Understanding OOP is a prerequisite for k1.prog.design-patterns and k1.prog.solid.

Practical Boundaries

Inheritance expresses "is-a / can substitute for," whereas composition expresses "has-a / delegates to a component." Duck typing does not require explicit inheritance, and true substitutability depends on exception semantics, return contracts, and state invariants—not just matching method names.

How It Works / Diagram

The four pillars of OOP:

Figure 1

Python's approach to OOP has several distinctive traits:

Trait Explanation
Everything is an object Integers, functions, and classes themselves are runtime objects (see k1.py.object-reference)
Encapsulation by convention No strict keyword-enforced private; a single leading underscore _x signals "internal use," while double underscores __x trigger name mangling
Duck typing "If it walks like a duck, it's a duck"—no explicit interface inheritance required; pair with typing.Protocol for static type checking
Abstract Base Classes abc.ABC + @abstractmethod prevent incomplete subclasses from being instantiated

Python Official Tutorial — Classes: https://docs.python.org/3/tutorial/classes.html ; abc module documentation: https://docs.python.org/3/library/abc.html

Runnable Example

# File: examples/05_oop.py
# Four pillars of OOP: Encapsulation, Inheritance, Polymorphism, Abstraction
from abc import ABC, abstractmethod

class Shape(ABC):                      # Abstraction: defines "what it can do"
    @abstractmethod
    def area(self) -> float: ...
    def describe(self):
        return f"{type(self).__name__} area={self.area():.2f}"

class Circle(Shape):                   # Inheritance
    def __init__(self, r): self._r = r # Encapsulation: leading underscore marks internal attribute
    def area(self): return 3.14159 * self._r ** 2

class Rect(Shape):
    def __init__(self, w, h): self.w, self.h = w, h
    def area(self): return self.w * self.h

for s in [Circle(1), Rect(2, 3)]:      # Polymorphism: same call, type-specific behavior
    print(s.describe())

try:
    Shape()
except TypeError as e:
    print("Abstract class cannot be instantiated:", e)

# Composition over inheritance: a Car "has an" Engine rather than "is an" Engine
class Engine:
    def start(self): return "Engine started"
class Car:
    def __init__(self): self.engine = Engine()
    def drive(self): return self.engine.start() + " -> Rolling"
print(Car().drive())

Captured output (Python 3.15.0):

Circle area=3.14
Rect area=6.00
Abstract class cannot be instantiated: Can't instantiate abstract class Shape without an implementation for abstract method 'area'
Engine started -> Rolling

Notice the third line: the abstract class Shape cannot be instantiated directly—Python raises a TypeError at object creation time if a required @abstractmethod like area is missing.

Common Pitfalls

  • Deep inheritance hierarchies: Five or six levels of subclassing make it hard to trace where a method is actually defined. "Favor object composition over class inheritance" is one of the foundational principles from Design Patterns (GoF, 1994)—in the example above, a Car has an Engine rather than is an Engine.
  • Wrapping everything in a class: A class with only one method alongside __init__ and no meaningful lifecycle state should usually just be a plain function. Jack Diederich's PyCon 2012 talk Stop Writing Classes covers this anti-pattern directly: https://www.youtube.com/watch?v=o9pEzgHorH0
  • Java-style getter/setter boilerplate: Python's @property decorator lets you add validation later without breaking attribute access syntax, so avoid writing get_x()/set_x() upfront.
  • Assuming objects must mirror physical real-world nouns: Many of the most useful objects represent purely technical abstractions (iterators, context managers, retry policies) rather than physical things.

Connection to AI Development

  • PyTorch models are stateful objects: In class MyNet(nn.Module), __init__ registers sub-layers (state = trainable parameters) and forward defines computation, while model.train()/eval() toggles internal mode flags. https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html
  • scikit-learn's estimator interface (fit / predict / transform) is a textbook application of polymorphism: swapping algorithms requires changing only the class constructor while downstream pipeline code stays untouched. https://scikit-learn.org/stable/developers/develop.html
  • LLM provider abstractions: Wrapping OpenAI, Claude, and local inference endpoints behind a unified polymorphic client interface keeps business logic decoupled from any single vendor SDK.

Further Reading

Concept Check

If two LLM client classes both expose a chat method, can they be swapped directly without further checks?

Reference answer: Only after confirming that their parameter semantics, return types, exception contracts, and resource lifecycles also match; sharing a method name is only the starting point.

Verification & Reproduction

Verified on: 2026-10-14. Example status: Passed. Run log: 05_oop.py.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram