From the free course Intro to Python Fundamentals on Lykke

Unit 6: Object-Oriented Programming (OOP)

Key concepts: Classes and Objects · Instance Attributes and State · Methods and Encapsulation · Special Methods (Dunder Methods) · Object Composition

Introduces the OOP paradigm to model real-world entities using classes and objects.

Unit 6: Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) represents a fundamental shift in the architecture of software. While procedural programming focuses on the sequence of actions (the "how"), OOP focuses on the entities involved (the "what"). By bundling data and the logic that manipulates that data into cohesive units called objects, we create a system that is modular, extensible, and significantly easier to reason about as complexity scales.

1. Classes and Objects: The Blueprint and the Instance

At its core, OOP is a method of abstraction. We define a Class as a programmer-defined blueprint from which individual Objects are created. If a class is the architectural drawing of a house, the object is the physical house built on a specific lot.

What it is

A Class is a logical grouping of data and functions. Mathematically, we can view a class $C$ as a set of potential states $S$ and a set of transitions $M$ (methods) that operate on those states. An Object (or instance) is a concrete realization of that class, occupying a specific block of memory and holding its own unique state.

Why it matters

In large-scale systems, managing global state is a recipe for disaster. OOP solves this by localizing state. Instead of having a variable player_health floating in global scope, it is encapsulated within a Player object. This prevents "spaghetti code" where a change in one part of the program causes unpredictable side effects elsewhere.

How it works: The Instantiation Pipeline

  1. Definition: The interpreter reads the class definition and stores it in memory.
  2. Allocation: When ClassName() is called, the system allocates memory for a new instance.
  3. Initialization: The __init__ method is automatically invoked to set the starting state.
  4. Reference: A reference (memory address) is returned to the variable name.
Concept Description Analogy
Class The template/type definition. The recipe for a cake.
Object The specific instance in memory. The actual cake on your plate.
Instantiation The process of creating an object. Baking the cake.
Type The classification of the object. "Chocolate Cake" vs "Sponge Cake".
# First code block: Low-level implementation of a complex system
# Modeling a Network Socket Connection with state management

class SecureSocket:
    """A high-level abstraction for a network socket with encryption state."""
    
    def __init__(self, host: str, port: int):
        self.address = (host, port)
        self.is_connected = False
        self.buffer = []
        self._encryption_key = None  # Internal state

    def connect(self):
        # Logic to establish a handshake
        print(f"Establishing connection to {self.address[0]}...")
        self.is_connected = True
        self._encryption_key = "0xDEADBEEF" # Simulated key exchange

    def send_data(self, payload: str):
        if not self.is_connected:
            raise ConnectionError("Socket must be connected before sending.")
        encrypted = f"[{self._encryption_key}] {payload}"
        self.buffer.append(encrypted)
        print(f"Data buffered: {encrypted}")

# Usage
client = SecureSocket("127.0.0.1", 8080)
client.connect()
client.send_data("Hello, Server!")

2. Instance Attributes and State

The "State" of an object is defined by its Attributes. These are variables that are bound to a specific instance of a class.

The self Keyword

In Python, self is the conventional name for the first parameter of an instance method. It represents the specific instance being acted upon. When you call object.method(), Python automatically passes object as the first argument.

The State Theorem: For any object $O$ of class $C$, the state at time $t$, denoted as $\sigma(O, t)$, is the mapping of all instance attributes to their current values. The behavior of $O$ is a function of both its inputs and its current state $\sigma$.

Class vs. Instance Attributes

It is vital to distinguish between attributes that belong to the class and those that belong to the instance.

Attribute Type Scope Memory Usage Common Use Case
Instance Attribute Unique to each object. Allocated per object. Names, IDs, health points, coordinates.
Class Attribute Shared by all instances. Allocated once for the class. Constants, configuration, instance counters.
# Second code block: Mathematical/Pseudocode representation of Object State

Definition: Object(S, M)
Let S = {a_1: v_1, a_2: v_2, ... a_n: v_n} be the set of Instance Attributes (State).
Let M = {f_1, f_2, ... f_m} be the set of Methods (Transitions).

Transition Function:
f_i(S, inputs) -> (S', output)

Example: BankAccount
S = {balance: 100}
M = {deposit(amount)}

deposit(S, 50):
    S.balance = S.balance + 50
    Return S' where S'.balance = 150

3. Methods and Encapsulation

Methods define the behavior of an object. Encapsulation is the practice of hiding the internal details of how an object works and exposing only what is necessary through a public interface.

Mechanics of Encapsulation

In many languages (like Java or C++), encapsulation is enforced by keywords like private or protected. Python follows a "consenting adults" philosophy:

  • Public: attribute (Accessible from anywhere).
  • Protected: _attribute (A hint that it is internal; should not be accessed outside the class).
  • Private: __attribute__ (Triggers Name Mangling to prevent accidental overrides in subclasses).

Why Encapsulation Matters

  1. Integrity: Prevents external code from setting an object into an invalid state (e.g., setting a BankAccount balance to a negative number).
  2. Abstraction: The user of the class doesn't need to know how the data is stored, only how to interact with it.
  3. Maintainability: You can change the internal implementation (e.g., switching from a list to a dictionary) without breaking external code that uses the object.
# Third code block: Real-world usage via CLI and Environment
# Demonstrating how an OOP-based SDK might be configured and used

# 1. Set up environment
export API_KEY="sk-12345"
export DB_URL="postgres://user:pass@localhost:5432/prod"

# 2. Pseudocode for a CLI tool using an OOP Controller
# $ python-cli upload --file data.csv --target s3://my-bucket

# Inside the implementation:
# storage = S3Backend(bucket="my-bucket")
# storage.authenticate(os.getenv("API_KEY"))
# storage.upload("data.csv")

4. Special Methods (Dunder Methods)

Dunder Methods (Double Underscore methods) are the "magic" hooks that allow your custom objects to interact with Python's built-in syntax. They implement what is known as the Python Data Model.

Common Dunder Methods

By implementing these, you make your objects feel like native Python types.

Method Purpose Triggered By
__init__ Constructor obj = ClassName()
__str__ User-friendly string print(obj) or str(obj)
__repr__ Developer-friendly string Inspecting in REPL or repr(obj)
__len__ Returns length len(obj)
__add__ Operator overloading obj1 + obj2
__getitem__ Indexing/Slicing obj[key]

Worked Example: A Vector Class

Consider a 2D Vector. Without dunder methods, adding two vectors would look like v1.add(v2). With __add__, it becomes v1 + v2, which is much more readable.

# Fourth code block: Dunder methods and Operator Overloading

class Vector2D:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        if not isinstance(other, Vector2D):
            return NotImplemented
        return Vector2D(self.x + other.x, self.y + other.y)

    def __repr__(self):
        return f"Vector2D({self.x}, {self.y})"

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

# Execution
v1 = Vector2D(2, 3)
v2 = Vector2D(4, 5)
v3 = v1 + v2  # Triggers __add__
print(v3)     # Triggers __repr__ -> Vector2D(6, 8)

5. Object Composition

Composition is a design principle where a complex object is built by combining simpler objects. It represents a "has-a" relationship.

Composition vs. Inheritance

While Inheritance ("is-a") allows a class to derive features from a parent, it often leads to rigid hierarchies. Composition is more flexible. A Car is not a Wheel, but a Car has Wheels.

The Composition Principle: Favor object composition over class inheritance. By composing objects, you can change behavior at runtime by swapping out component objects, whereas inheritance is fixed at compile-time.

Implementation Mechanics

In composition, one object holds a reference to one or more other objects as attributes.

# Fifth code block: Object Composition in a Game Engine context

class Engine:
    def start(self):
        return "Engine roaring to life..."

class Tires:
    def __init__(self, pressure):
        self.pressure = pressure

class Car:
    def __init__(self, model):
        self.model = model
        # Composition: Car HAS AN Engine and HAS Tires
        self.engine = Engine()
        self.tires = [Tires(32) for _ in range(4)]

    def drive(self):
        status = self.engine.start()
        return f"The {self.model} is moving. {status}"

# Usage
my_tesla = Car("Model 3")
print(my_tesla.drive())

6. Common Pitfalls and Best Practices

  1. Mutable Class Attributes: Defining a list as a class attribute means all instances share that same list. If one object appends to it, it changes for everyone. Always initialize mutable data inside __init__.
  2. The "God Object": Avoid creating classes that do too much. A class should have a Single Responsibility.
  3. Over-Engineering: Don't use OOP for simple scripts where a few functions would suffice. OOP adds boilerplate that is only justified by complexity.
  4. Privacy Misconceptions: Remember that _variable doesn't actually stop someone from accessing it; it is a social contract. If you need true security, Python is the wrong language.

Summary Table: The OOP Paradigm

Feature Description Benefit
Abstraction Hiding complex logic behind simple interfaces. Reduces cognitive load.
Encapsulation Bundling data and methods; restricting access. Protects data integrity.
Modularity Dividing a program into independent objects. Easier debugging and testing.
Reusability Using classes across different projects. Saves development time.

By mastering these concepts, you move from writing "scripts" to engineering "systems." OOP provides the scaffolding necessary to build software that can grow, adapt, and persist in professional environments.

Unit 6: Object-Oriented Programming (OOP) - Intro to Python Fundamentals - image 1
Unit 6: Object-Oriented Programming (OOP) - Intro to Python Fundamentals - image 1
Unit 6: Object-Oriented Programming (OOP) - Intro to Python Fundamentals - diagram 1
Unit 6: Object-Oriented Programming (OOP) - Intro to Python Fundamentals - diagram 1
Unit 6: Object-Oriented Programming (OOP) - Intro to Python Fundamentals - diagram 2
Unit 6: Object-Oriented Programming (OOP) - Intro to Python Fundamentals - diagram 2

Source Materials

Study Intro to Python Fundamentals on Lykke

This course page is free to open: signed out, you can read its first two sections, and signing in, on any plan, opens the rest. The free Lykke Chrome extension syncs your own Canvas courses, so ChatGPT, Claude and Muse can answer from your classes and deadlines. It only reads Canvas.

Add the free extensionSign in to open every section

All sections of Intro to Python Fundamentals · Browse more course pages