What is Object-Oriented Programming?
Chapter 1: What is Object-Oriented Programming?
Welcome to Lesson 9! So far, you have learned how to write Python code using variables, conditions, loops, functions, and even how to handle errors. But as your programs grow, you will notice that keeping everything in separate functions and variables can become messy. Imagine building a task management API with hundreds of tasks, users, and categories. How do you keep all that data organized? This is where Object-Oriented Programming (OOP) comes in.
What is OOP?
Object-Oriented Programming is a way of writing code that groups related data and actions together into objects. Think of an object as a small, self-contained program that has its own information (called attributes) and its own behaviors (called methods). For example, a Task object might have attributes like title, description, and completed, and methods like mark_complete() or display().
OOP helps you write code that is easier to understand, reuse, and maintain. It is especially useful when building real-world applications like REST APIs.
Why Do We Need OOP?
- Organization: Instead of having many separate variables and functions, you group related things together.
- Reusability: You can create a blueprint (called a class) and then create many objects from that blueprint.
- Real-world modeling: OOP lets you model real-world things (like a user, a task, or a car) directly in your code.
- Scalability: As your project grows, OOP makes it easier to add new features without breaking existing code.
Key Concepts: Class and Object
A class is like a blueprint or a template. It defines what attributes and methods an object will have. An object is a specific instance of that class. For example, the class Task defines the structure, and task1 = Task() creates an actual task object.
Step-by-Step: Your First Class
Let's create a simple class called Task that represents a to-do item. We will give it two attributes: title and completed. We will also add a method to mark the task as complete.
# Define the class
class Task:
# The __init__ method is called when we create a new object
def __init__(self, title):
self.title = title # attribute
self.completed = False # attribute, default is False
# A method to mark the task as complete
def mark_complete(self):
self.completed = True
# A method to display the task
def display(self):
status = "✓" if self.completed else "✗"
print(f"[{status}] {self.title}")
# Create an object (instance) of the Task class
task1 = Task("Learn Python OOP")
task1.display() # Output: [✗] Learn Python OOP
# Mark it complete
task1.mark_complete()
task1.display() # Output: [✓] Learn Python OOP
Explanation of the Code
class Task:This defines a new class namedTask.def __init__(self, title):This is the constructor method. It runs automatically when you create a new object. Theselfparameter refers to the current object.self.title = titleandself.completed = Falseare attributes. They store data for each object.def mark_complete(self):anddef display(self):are methods. They define behaviors.task1 = Task("Learn Python OOP")creates an object. The string is passed to the__init__method.
Common Mistakes for Beginners
- Forgetting
self: Every method inside a class must haveselfas its first parameter. Without it, Python will raise an error. - Confusing class and object: The class is the blueprint; the object is the actual thing you use. You cannot call methods on the class itself (unless they are class methods, which we will cover later).
- Not using
__init__properly: The__init__method is where you set up initial attributes. If you forget to define it, your object will not have the expected attributes.
Practical Example: A Simple User Class
Let's build a User class that we might use later in our API. It will have a username, email, and a list of tasks.
class User:
def __init__(self, username, email):
self.username = username
self.email = email
self.tasks = [] # empty list to hold Task objects
def add_task(self, task_title):
new_task = Task(task_title)
self.tasks.append(new_task)
print(f"Task '{task_title}' added for {self.username}")
def show_tasks(self):
print(f"Tasks for {self.username}:")
for task in self.tasks:
task.display()
# Create a user
user1 = User("ahmed", "ahmed@example.com")
user1.add_task("Buy groceries")
user1.add_task("Read a book")
user1.show_tasks()
Notice how we reused the Task class inside the User class. This is the power of OOP: you can combine objects to build more complex systems.
Why This Matters for Your API
In the coming lessons, you will build a real REST API for managing tasks. You will use classes to represent tasks, users, and other entities. OOP will help you keep your code clean and organized as your project grows. For example, you will have a Task class that holds data and methods, and you will create many task objects to represent different to-do items.
Your Practice Task
Create a class called Book that has the following attributes: title, author, and pages. Add a method called summary() that prints a string like: "Title: [title], Author: [author], Pages: [pages]". Then create two book objects and call the summary() method on each.
Try to do this on your own before looking at the solution below.
# Solution
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def summary(self):
print(f"Title: {self.title}, Author: {self.author}, Pages: {self.pages}")
book1 = Book("1984", "George Orwell", 328)
book2 = Book("To Kill a Mockingbird", "Harper Lee", 281)
book1.summary()
book2.summary()
Great job! You have just taken your first step into Object-Oriented Programming. In the next lesson, we will dive deeper into how to organize your Python projects using packages and virtual environments, which will prepare you for building your API.

Loading ratings...