Skip to main content

Python Development Crash Guide 2026 — Part 3: Advanced Python: OOP, Decorators, Generators & Memory Model

Python Crash Guide · Part 3 of 6 · ~18 min read · December 2025


Python Development Crash Guide 2026 — Part 3: OOP, Decorators, Generators & Memory Model

This part of the guide covers the topics that separate someone who writes Python from someone who thinks in Python. OOP, decorators, generators, and memory management — these are the building blocks that show up in every serious codebase, and they're the concepts interviewers zero in on because they reveal whether you actually understand what's happening under the hood.

Coming from Java, most of this felt simultaneously familiar and alien. The OOP concepts map roughly to what I already knew — but the implementation philosophy is completely different. Java enforces structure through the compiler. Python trusts you to be an adult and gives you sharper tools with fewer guardrails. That's both liberating and dangerous.


Classes Beyond the Basics

If you've written Java, you already know classes. But Python classes have a few quirks that will trip you up if you're not expecting them.

Everything is public (sort of)

Java has private, protected, public — enforced by the compiler. Python has a convention: a single underscore prefix (_internal_method) means "don't touch this from outside." A double underscore prefix (__mangled) triggers name mangling — Python renames it to _ClassName__mangled — but it's still accessible. Nothing is truly private.

This bothered me at first. Then I realised Python's philosophy is "we're all consenting adults." The underscore convention works because the community respects it. And honestly, after years of writing Java getters/setters that added zero value, the Python approach feels more honest about what access control actually achieves.

class UserService:
    def __init__(self, db_connection):
        self.db = db_connection          # public
        self._cache = {}                  # "private" by convention
        self.__secret_key = "abc123"     # name-mangled (still accessible)

    def get_user(self, user_id):
        if user_id in self._cache:
            return self._cache[user_id]
        user = self.db.fetch(user_id)
        self._cache[user_id] = user
        return user

Properties replace getters/setters

Instead of the Java pattern of private field + public getter + public setter, Python uses the @property decorator. You start with a plain attribute, and if you later need validation or computation, you wrap it in a property without changing the calling code. This is a genuine improvement over Java's approach:

class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius

    @property
    def fahrenheit(self):
        return self._celsius * 9 / 5 + 32

    @fahrenheit.setter
    def fahrenheit(self, value):
        self._celsius = (value - 32) * 5 / 9

t = Temperature(100)
print(t.fahrenheit)    # 212.0 — looks like an attribute, runs a method

Inheritance and the MRO Problem

Python supports multiple inheritance. Java doesn't (it uses interfaces instead). This sounds like a feature until you hit the diamond problem — two parent classes that inherit from the same grandparent. Which version of the method gets called?

Python solves this with the C3 linearisation algorithm, which produces the Method Resolution Order (MRO). You can inspect it with ClassName.__mro__ or ClassName.mro().

class Base:
    def greet(self):
        return "Base"

class A(Base):
    def greet(self):
        return "A"

class B(Base):
    def greet(self):
        return "B"

class C(A, B):
    pass

print(C().greet())  # "A" — MRO is C → A → B → Base → object
print(C.__mro__)    # inspect the full resolution order

In practice, I rarely use multiple inheritance directly. What I use instead is mixins — small, focused classes that add a single capability. Think of them like Java interfaces with default methods, but more flexible:

class JsonSerializableMixin:
    def to_json(self):
        import json
        return json.dumps(self.__dict__)

class LoggableMixin:
    def log(self, message):
        print(f"[{self.__class__.__name__}] {message}")

class User(JsonSerializableMixin, LoggableMixin):
    def __init__(self, name, email):
        self.name = name
        self.email = email

Composition over inheritance — the same lesson from Java applies

The Gang of Four advice applies equally in Python: favour composition over inheritance. Deep inheritance hierarchies are hard to reason about in any language. In Python, where there's no compiler to catch type mismatches, they're even more dangerous.

Instead of inheriting from a DatabaseConnection class, inject one. Instead of building a class hierarchy for different notification types, pass a strategy function. Python makes composition easy because functions are first-class objects — you can pass them around, store them, and call them later.


Abstract Base Classes — Python's Version of Java Interfaces

Python's duck typing means you don't need interfaces — if an object has a quack() method, it's a duck. But sometimes you want to enforce a contract, especially in larger codebases. That's where Abstract Base Classes come in:

from abc import ABC, abstractmethod

class PaymentProcessor(ABC):
    @abstractmethod
    def charge(self, amount: float) -> bool:
        """Process payment. Return True if successful."""
        ...

    @abstractmethod
    def refund(self, transaction_id: str) -> bool:
        ...

class StripeProcessor(PaymentProcessor):
    def charge(self, amount):
        # Stripe-specific implementation
        return True

    def refund(self, transaction_id):
        return True

If you come from Spring Boot, think of ABCs as Python's equivalent of defining a service interface. In Spring you'd have a PaymentService interface and inject the implementation via DI. In Python, you'd have an ABC and pass the implementation explicitly. The pattern is the same — the wiring mechanism is different.


Dataclasses — Stop Writing Boilerplate

If you've ever written a Java POJO — constructor, equals, hashCode, toString — and wished someone would automate it, Python's dataclasses are exactly that. (Java got records in Java 16, but Python had this first.)

from dataclasses import dataclass, field

@dataclass
class Order:
    order_id: str
    customer: str
    total: float
    items: list = field(default_factory=list)

    def add_item(self, item):
        self.items.append(item)

# Auto-generates __init__, __repr__, __eq__
order = Order("ORD-001", "Alice", 59.99)
print(order)  # Order(order_id='ORD-001', customer='Alice', total=59.99, items=[])

Notice field(default_factory=list) instead of items: list = []. Remember the mutable default argument trap from Part 1? This is how you avoid it in dataclasses. The factory creates a new list for each instance instead of sharing one across all instances.

For API work, I've mostly switched to Pydantic models instead of plain dataclasses — they add validation and serialisation out of the box. But understanding dataclasses is still essential because they're in the standard library and appear everywhere.


Decorators — the Concept That Unlocks Python

Decorators confused me for weeks when I first learned Python. Not because the concept is hard — it's just functions wrapping functions — but because tutorials explain the mechanism without explaining why you'd want it.

So let me start with the "why": decorators let you add behaviour to a function without modifying the function itself. If you know Java annotations like @Transactional or @Cacheable in Spring, decorators are the same idea — except they're not magic. You can read the source code and understand exactly what's happening.

The basic pattern

import time
import functools

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed = time.perf_counter() - start
        print(f"{func.__name__} took {elapsed:.4f}s")
        return result
    return wrapper

@timer
def fetch_users(db):
    return db.query("SELECT * FROM users")

# When you call fetch_users(db), it automatically prints the execution time

The @functools.wraps(func) line is critical and often left out of tutorials. Without it, the wrapper replaces the original function's name and docstring, which breaks introspection, logging, and debugging. Always include it.

Decorators with arguments

This is where it gets tricky — you need an extra layer of nesting. Here's a retry decorator I actually use in production:

def retry(max_attempts=3, delay=1.0):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(1, max_attempts + 1):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    if attempt == max_attempts:
                        raise
                    print(f"Attempt {attempt} failed: {e}. Retrying...")
                    time.sleep(delay)
        return wrapper
    return decorator

@retry(max_attempts=5, delay=2.0)
def call_external_api(endpoint):
    # If this fails, it retries up to 5 times with 2s delay
    return requests.get(endpoint).json()

Compare this to Spring's @Retryable annotation. The idea is identical — cross-cutting concern applied declaratively. But in Python, you can read the implementation. No proxy objects, no AOP weaving, no Spring magic. It's just functions all the way down.

Real-world decorator uses

In production codebases, I see decorators used for: authentication and authorization checks, input validation, caching (like @functools.lru_cache), rate limiting, logging and metrics, and retry logic. Flask and FastAPI route definitions (@app.route("/users")) are decorators too.


Closures — Functions That Remember

A closure is a function that captures variables from its enclosing scope. Decorators are actually closures. But closures have other practical uses:

# Function factory — returns a configured function
def make_multiplier(factor):
    def multiply(x):
        return x * factor   # 'factor' is captured from the enclosing scope
    return multiply

double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5))   # 10
print(triple(5))   # 15

The practical version of this pattern shows up when you need stateful functions — say, a counter or a rate limiter that doesn't need a full class:

def make_counter(start=0):
    count = [start]    # list because we need mutability
    def increment():
        count[0] += 1
        return count[0]
    return increment

counter = make_counter()
print(counter())  # 1
print(counter())  # 2

In Python 3, you can also use the nonlocal keyword instead of the list trick: nonlocal count lets you rebind a variable in the enclosing scope directly.


Iterators and Generators — Python's Superpower

If decorators are what make Python code clean, generators are what make it efficient. This is one area where Python genuinely outshines Java's traditional approach (though Java Streams have closed the gap).

The iterator protocol

Any object that implements __iter__() and __next__() is an iterator. Python's for loop uses this protocol under the hood — it calls __next__() until StopIteration is raised. You can build custom iterators, but generators are almost always better.

Generators with yield

A generator is a function that uses yield instead of return. It produces values one at a time, on demand, without holding the entire sequence in memory. This is lazy evaluation — the work happens only when you ask for the next value.

# Without generators — loads entire file into memory
def read_all_lines(filepath):
    with open(filepath) as f:
        return f.readlines()   # entire file in memory at once

# With generators — one line at a time
def read_lines(filepath):
    with open(filepath) as f:
        for line in f:
            yield line.strip()    # one line in memory at a time

# Process a 10GB log file without running out of memory
for line in read_lines("huge_access.log"):
    if "ERROR" in line:
        print(line)

I use generators constantly for processing large datasets, streaming API responses, and building data pipelines. They're the reason Python can handle files that don't fit in memory — something that takes significantly more boilerplate in Java.

Generator expressions

Just as list comprehensions create lists, generator expressions create generators. The syntax is identical except you use parentheses instead of square brackets:

# List comprehension — creates entire list in memory
squares_list = [x**2 for x in range(1_000_000)]

# Generator expression — computes each value on demand
squares_gen = (x**2 for x in range(1_000_000))

# Use generators when you're only iterating once
total = sum(x**2 for x in range(1_000_000))  # memory-efficient

Python's Memory Model — What You Need for Interviews

This comes up in interviews more than you'd expect. Understanding how Python manages memory separates confident answers from uncertain ones.

Reference semantics everywhere

We covered the basics in Part 1, but let me go deeper. Every variable in Python is a reference (pointer) to an object on the heap. Assignment never copies the object — it copies the reference.

import copy

original = [[1, 2], [3, 4]]

# Shallow copy — new outer list, same inner lists
shallow = copy.copy(original)
shallow[0].append(99)
print(original)     # [[1, 2, 99], [3, 4]] — inner list was shared!

# Deep copy — completely independent copy
deep = copy.deepcopy(original)
deep[0].append(999)
print(original)     # [[1, 2, 99], [3, 4]] — original is unchanged

This shallow-vs-deep copy distinction is one of the most common interview questions, and one of the most common sources of bugs in production code. My rule of thumb: if you're passing data between functions and don't want side effects, use copy.deepcopy() or work with immutable types.

Garbage collection

Python uses reference counting as its primary garbage collection mechanism — when an object's reference count drops to zero, it's immediately deallocated. This is different from Java's GC, which runs periodically and can cause pause spikes.

Reference counting can't handle circular references (A points to B, B points to A, nothing else points to either). For that, Python has a secondary cycle detector that periodically scans for unreachable reference cycles.

Interview tip: If asked "how does Python manage memory," cover three things: reference counting for the common case, the cycle detector for circular references, and the small-integer cache (Python pre-allocates integers from -5 to 256, so a = 256; b = 256; a is b returns True, but a = 257; b = 257; a is b may not). Mentioning the third point shows you've dug deeper than the textbook answer.


What's Next

This was the most concept-heavy part of the series. If decorators and generators feel abstract right now, that's normal — they click once you start using them in real projects. In Part 4, we shift to the practical side: modules, packages, virtual environments, and how to structure a Python project that doesn't turn into a mess at scale.


Series Navigation


About the author: I'm Prashant Sharma — a backend Tech Lead working with Java/Spring Boot in production. I teach Python and Java on YouTube and run 1:1 sessions on Topmate.

Comments