Back to Blog
Lesson 45 of the Python: Programming from Zero with Python course
PythonSeptember 2, 20263 min read

Introduction to Object-Oriented Programming (OOP) in Python

Learn the fundamentals of OOP in Python. Discover how to define classes, create instances (objects), and use the __init__ constructor to structure your code.

PythonOOPclassesobjectsprogramming-fundamentals
A person reads 'Python for Unix and Linux System Administration' indoors.

Previously in this course, we explored Query Parameters and Path Variables to make our FastAPI endpoints more dynamic. Now, we shift from procedural scripting toward Object-Oriented Programming (OOP), a paradigm that helps us organize complex data and behaviors into reusable, logical structures.

While we've used functions to organize logic (as covered in Defining Custom Functions), OOP allows us to bundle data and the functions that operate on that data into a single entity.

Understanding Classes and Objects

Think of a class as a blueprint. If you were building a house, the blueprint isn't the house itself; it’s the design that dictates where the walls, doors, and windows go.

An object (or instance) is the actual house built from that blueprint. You can build dozens of houses from the same blueprint, each with its own unique address or color, even though they share the same fundamental structure.

In Python, we use the class keyword to define our blueprint.

Defining Your First Class

Let's start by defining a DataEntry class. In our ongoing project, we’ve handled data as dictionaries, but as our app grows, dictionaries become prone to errors (like typos in keys). A class provides a rigid structure.

PYTHON
class DataEntry:
    def __init__(self, id, value):
        self.id = id
        self.value = value

The __init__ Method: The Constructor

The __init__ method is a special function called automatically when you create a new instance of a class. It stands for "initialize."

  • self: This represents the specific object currently being created. It allows the class to distinguish between "my ID" and "your ID."
  • Parameters: We pass id and value to initialize the object's specific data.
  • Assignment: self.id = id takes the value provided during creation and stores it inside the object as an attribute.

Creating Objects (Instances)

Once the class is defined, we can create as many objects as we need. This process is called instantiation.

PYTHON
# Creating instances of our class
entry1 = DataEntry(1, "Temperature: 22C")
entry2 = DataEntry(2, "Humidity: 45%")

# Accessing attributes
print(entry1.value)  # Output: Temperature: 22C
print(entry2.value)  # Output: Humidity: 45%

Hands-on Exercise

Create a file named processor.py. Define a class called Sensor that takes name and location in its __init__ method. Instantiate two different sensors (e.g., a "Thermometer" in the "Living Room" and a "Barometer" in the "Basement"). Finally, print the location of the second sensor.

Common Pitfalls

  1. Forgetting self: Beginners often omit self as the first argument in __init__. Without it, Python won't know which object's attributes to update.
  2. Confusing Classes and Instances: Remember, you cannot access DataEntry.value directly because the class itself doesn't have a value—only the instances do.
  3. Naming Collisions: Keep your class names descriptive and use PascalCase (e.g., DataEntry instead of data_entry).

FAQ

Why use classes instead of dictionaries? Classes allow you to attach behaviors (methods) directly to your data. They also provide "type safety" because you can ensure all objects of a certain class have the same required attributes.

Is __init__ mandatory? No, but it is standard practice. If you don't define it, Python provides a default empty constructor.

What is the difference between an attribute and a variable? An attribute is simply a variable that is bound to an object.

Recap

We have moved from procedural code to OOP by defining classes as blueprints and creating objects as instances. We used the __init__ method to ensure every new object starts with the necessary data. Mastering these concepts is the first step toward building the robust, maintainable systems that characterize professional backend development.

Up next: Methods and Attributes — we will learn how to add custom behaviors to our classes using instance methods and the self keyword.

Similar Posts