Untitled

Python Object-Oriented Programming (OOP)

1. What is Object-Oriented Programming, and why does it exist?

Object-Oriented Programming (OOP) is a programming approach that organizes software around objects that combine related data and behavior.

Until now, we have mainly written procedural programs using variables, functions, conditionals, loops, lists, and dictionaries.

Procedural programming: Organizes a program around functions and sequences of instructions.

Object-Oriented Programming: Organizes a program around objects that hold data and provide methods for working with that data.

Why was OOP introduced?

As applications become larger, managing many unrelated variables and functions becomes difficult.

OOP helps developers:

  • Organize related data and functionality.

  • Break complex applications into manageable components.

  • Reuse code by creating multiple objects from one class.

  • Hide implementation details behind clear interfaces.

  • Maintain and extend applications more easily.

Mental model: Instead of one large program doing everything, imagine several smaller components working together, each responsible for a specific task.

OOP is one approach to software organization, not a requirement for every Python program.

Bigger picture — AI/ML engineering

Imagine building an ML application that trains several fraud-detection models.

Rather than scattering model settings and operations across your code, you could create an MLModel class that stores a model's name, training state, and methods.

This same organizational idea appears throughout scikit-learn, PyTorch, and AI agent frameworks.

Remember: OOP helps manage software complexity by combining related data and behavior into reusable objects.


2. Classes vs. Objects

Class: A blueprint or template defining the attributes and methods that its objects can have.

Object: A specific instance created from a class.

Instance: Another word for an object created from a class.

The cookie-cutter analogy

  • Class = cookie cutter.

  • Object = individual cookie.

  • One cookie cutter can produce many cookies.

  • One class can create many independent objects.

Python example

class Dog:
    def bark(self):
        print("Woof!")

dog1 = Dog()
dog2 = Dog()

dog1.bark()

Dog is the class.

dog1 and dog2 are two separate objects created from that class.

bark() is a method belonging to the class.

Key distinction: Defining a class does not automatically create an instance of that class. Calling Dog() creates an object.

Bigger picture — ML models

model = RandomForestClassifier()

Here, RandomForestClassifier is a class from scikit-learn, and model references an instance of that class.

You can create multiple model objects with different configurations.

Remember: Class = blueprint. Object = instance created using the blueprint.


3. Attributes and Methods — Data + Behavior

Objects combine two important concepts.

Attribute (or field): Data associated with an object.

Method: A function defined inside a class that describes behavior.

Example:

class Student:
    def __init__(self, name):
        self.name = name
        self.score = 0

    def study(self):
        self.score += 10

student = Student("Alex")
student.study()

print(student.score)

Output:

10

In this example:

  • name and score are instance attributes.

  • study() is a method.

  • student is an object.

  • student.score accesses the object's data.

  • student.study() calls its behavior.

Connection to previous Python knowledge

You've already used objects throughout the course:

numbers = [3, 1, 2]
numbers.sort()

word = "hello"
word.upper()

counts = {"a": 2}
counts.items()

Lists, strings, and dictionaries are Python objects.

.sort(), .upper(), and .items() are methods.

You were using OOP concepts before formally learning their terminology.

Remember: Attributes describe an object's state; methods describe what it can do.


4. Understanding self and the Dot Operator

self refers to the particular instance on which an instance method is operating.

It allows methods to access or change that object's attributes.

class Counter:
    def __init__(self):
        self.count = 0

    def increase(self):
        self.count += 1

a = Counter()
a.increase()
a.increase()

print(a.count)

Output:

2

What happens?

  1. Counter() creates an object.

  2. __init__ initializes its count to zero.

  3. a.increase() calls the object's method.

  4. Inside the method, self refers to the object referenced by a.

  5. self.count updates that object's count.

Python automatically supplies the instance when calling an ordinary instance method using a.increase().

Dot operator (.)

The dot operator accesses attributes or methods belonging to an object.

a.count       # Access attribute
a.increase()  # Call method

Connection to ML

model.fit(X_train, y_train)
predictions = model.predict(X_test)

.fit() and .predict() are methods belonging to the model object.

Understanding self, methods, and object state helps you understand how ML libraries are designed.

Remember: self identifies the current instance; the dot operator accesses its attributes and methods.


5. Constructors and Object Initialization

A constructor is involved in creating a new object.

In Python, __init__() is the initialization method automatically called during ordinary instance creation.

It sets up the object's initial state.

class MLModel:
    def __init__(self, name):
        self.name = name
        self.is_trained = False

    def train(self):
        self.is_trained = True
        print(f"{self.name} trained")

model = MLModel("Fraud Detector")
model.train()

Output:

Fraud Detector trained

Explanation

  • class MLModel defines the blueprint.

  • __init__ initializes the object.

  • self.name stores the model's name.

  • self.is_trained stores its current state.

  • train() changes the object's state.

This is a simplified demonstration of state management, not actual machine-learning training.

Why is initialization important?

Different objects may need different starting values.

For example, different ML models can have different names, settings, or hyperparameters.

Remember: __init__() prepares each new instance with its initial attributes.


6. Multiple Objects and Independent State

One class can create many objects.

Each object can maintain its own instance attributes.

class Counter:
    def __init__(self, name):
        self.name = name
        self.count = 0

    def increase(self):
        self.count += 1

a = Counter("A")
b = Counter("B")

a.increase()
a.increase()
b.increase()

print(a.count)
print(b.count)

Output:

2
1

Why are the values different?

Although both objects were created from the same class, each has its own count attribute.

Changing a.count does not change b.count.

This is a key difference between a class definition and the individual objects created from it.

Bigger picture

Imagine two ML model instances:

  • Model A is trained using one dataset.

  • Model B is trained using another dataset.

Each model object can maintain its own fitted parameters and configuration.

Remember: Objects created from the same class can hold different states.


7. Encapsulation and Interfaces

Encapsulation means organizing related data and behavior together and providing a defined way to interact with them.

An interface is the set of operations an object makes available to other code.

You often do not need to understand how a library works internally to use its methods correctly.

For example:

numbers.sort()

You know that .sort() sorts the list in place.

You do not need to implement Python's sorting algorithm yourself.

Why is this useful?

  • Reduces the amount of complexity developers must understand at once.

  • Separates internal implementation from external usage.

  • Makes components easier to reuse and maintain.

Python does not automatically make all object attributes private. Encapsulation is primarily about designing clear boundaries and responsibilities.

Bigger picture — AI applications

An AI application might have separate components for:

  • Calling an LLM.

  • Retrieving information.

  • Managing conversations.

  • Saving results to a database.

Each component can expose a small number of methods, allowing other components to use its functionality without understanding every internal detail.

Remember: Encapsulation helps developers manage complexity through clear component boundaries.


8. Object Lifecycle and Destructors

An object lifecycle describes the creation, use, and eventual destruction of an object.

Important methods:

  • __init__() — initializes an object.

  • __del__() — may be called when an object is being finalized.

Example:

class Example:
    def __init__(self):
        print("Created")

    def __del__(self):
        print("Finalized")

For now, focus on understanding __init__().

__del__() is less commonly needed, and its execution timing is not guaranteed across Python implementations.

Remember: Object initialization is essential; destructor details can be studied later.


9. Inspecting Objects — type() and dir()

Python provides tools for examining objects.

type() identifies an object's type.

dir() lists names of available attributes and methods.

Example:

numbers = [1, 2, 3]

print(type(numbers))
print(dir(numbers))

type(numbers) shows that the object is a list.

dir(numbers) includes methods such as append, sort, and pop.

Why is this useful?

When working with unfamiliar Python libraries, you can inspect an object to discover available operations.

However, documentation is still important for understanding what those operations do.

Remember: type() tells you what an object is; dir() helps you explore what it exposes.


10. OOP and the Bigger Picture — AI/ML Engineering

Object-Oriented Programming is a foundation for understanding many professional Python libraries.

Machine learning — scikit-learn

model = RandomForestClassifier()
model.fit(X_train, y_train)
predictions = model.predict(X_test)

The model is an object.

Its methods provide a consistent interface for training and prediction.

Deep learning — PyTorch

PyTorch neural networks are commonly defined as classes inheriting from nn.Module.

These classes organize neural-network layers, parameters, and forward computations.

AI agents

An agent application might use:

agent = AIAgent()
agent.run("Analyze this dataset")

This is an illustrative interface.

The agent class could coordinate an LLM, tools, external APIs, and database access.

Databases and APIs

As you study the remaining Python for Everybody chapters, you will encounter objects representing HTTP responses, database connections, and cursors.

OOP will help you understand how those libraries expose functionality.

Connection to software engineering

OOP is useful for building reusable, maintainable software, but not every task needs a class.

Small data-processing scripts are often clearer with ordinary functions.

The engineering skill is knowing when an object helps organize related state and behavior.


11. Essential OOP Terminology — Interview Recall

OOP: Programming approach that organizes related data and behavior into objects.

Class: Blueprint for creating objects.

Object: Instance of a class.

Instance attribute: Data belonging to an individual object.

Method: Function defined inside a class.

self: Reference to the current instance inside an instance method.

__init__: Method used to initialize an object.

Instantiation: Creating an instance from a class.

Encapsulation: Grouping data and behavior behind clear interfaces.

Object state: The values of an object's attributes at a particular time.

Dot operator: Syntax used to access an object's attributes and methods.

Inheritance: Mechanism allowing one class to derive behavior or attributes from another class. Useful to recognize now; study in more depth later.

Composition: Building more complex objects using other objects as components. Useful for structuring larger applications.


12. Final Mental Model

Think of a software application as a collection of cooperating components.

Procedural programming asks: What sequence of operations should the program perform?

Object-oriented programming asks: What objects should the system contain, what information should each maintain, and what responsibilities should each have?

Both approaches can be combined in Python.

The key purpose of OOP is not simply learning the class keyword. It is learning how to organize software into understandable, reusable components.

Career connection: This knowledge will help you understand ML frameworks, build AI applications, and progress from writing small Python scripts to designing maintainable software systems.