← Back to list

Mastering Object-Oriented Programming (OOP) in Python in Three Simple Ways — Part 1: OOP…

Programming is the process of creating instructions for a computer to execute. However, the way in which these instructions are organized…

Hasan Ash. · 2023-04-24 09:42 · 1 claps · 5.4 min read
#oop-python #oop-with-python #oop-python-example #oop-python-tutorial
Open on Medium ↗
Wiki topics: 💻 · Programming

Mastering Object-Oriented Programming (OOP) in Python in Three Simple Ways

Part 1: OOP Introduction

Programming is the process of creating instructions for a computer to execute. However, the way in which these instructions are organized and structured can vary depending on the programming paradigm used.

A programming paradigm is a way of thinking about and organizing code to solve a problem. There are several programming paradigms, such as procedural programming, functional programming, and object-oriented programming (OOP).

I will discuss OOP in Python through the articles which I will divide into 3 parts.

  1. The first part will discuss the introduction of OOP and how to use it in Python
  2. ***In the second part, I will show you how to design a class hierarchy to describe the application that we will build***
  3. The Third, the last section will discuss how to implement the class hierarchy into Python code

Now, lets deep dive into the first Part “Introduction of Object-Oriented Programming in Python”

What is OOP ?

Object-Oriented Programming (OOP) is a programming paradigm that uses objects to represent real-world entities and concepts. It is based on the concept of objects, which are instances of classes.

A class is a blueprint that defines the attributes and methods of an object. Attributes are the data that describes the object, while methods are the functions that the object can perform.

Here’s an analogy to explain the concepts of class, object, attribute, and method in Python:

Imagine you are building a car factory. The factory is the class, and it has a blueprint that describes how the cars should be built. This blueprint is like the class definition in Python.

Now, let’s say you want to build a car. You take the blueprint from the factory and use it to build a car. The car you built is like an object of the class.

Each car has its unique characteristics, such as its color, model, and year. These characteristics are like the attributes of an object in Python. For example, a car object might have attributes such as color=”red”, model=”SUV”, and year=2022.

Finally, let’s say you want to make the car do something, like drive. You press the gas pedal and the car moves. This action is like a method of an object in Python. For example, you might define a method in a car object called “drive” that makes the car move forward when called.

Why OOP?

OOP offers several benefits over other programming paradigms, such as procedural programming and functional programming. One of the main advantages of OOP is that it provides a more natural way of thinking about code. OOP allows programmers to model real-world entities and concepts as objects, making it easier to understand and modify code.

The other several advantages to using OOP in your programming projects are:

Modularity: OOP allows you to break down your program into smaller, more manageable modules. Each module represents a specific aspect of your program and can be designed, tested, and debugged separately from the rest of the program. This makes it easier to organize and maintain large and complex programs.

Reusability: OOP allows you to reuse code that has already been written, reducing the amount of time and effort required to develop a new program. This is achieved by using classes and objects, which can be instantiated and used in multiple programs.

Encapsulation: OOP encapsulates data and methods within an object, protecting them from outside interference. This means that the data and methods can only be accessed and modified by the object or other objects within the same class. This helps to prevent bugs and errors caused by accidental modification of data or methods.

Polymorphism: OOP allows you to create multiple objects of the same class, each with its unique properties and behaviors. This makes it easy to develop programs that can handle various input types and respond differently based on the type of input received.

Overall, OOP is a powerful programming paradigm that offers a range of benefits over other programming paradigms. By using OOP, you can write more modular, reusable, and maintainable code, making it easier to develop and maintain large and complex programs.

Example of OOP in Python

To further clarify your understanding of OOP, here are 3 examples of simple Python programs built using OOP functions and methods. I’ll explain each program and the differences between the functional and OOP implementations at the end of each section.

Example #1: Calculator

Using Function

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero!")
    return a / b

Using OOP

class Calculator:
    def add(self, a, b):
        return a + b

    def subtract(self, a, b):
        return a - b

    def multiply(self, a, b):
        return a * b

    def divide(self, a, b):
        if b == 0:
            raise ValueError("Cannot divide by zero!")
        return a / b

Explanation: The above programs implement a simple calculator that can perform addition, subtraction, multiplication, and division. The functional implementation defines each operation as a separate function, while the OOP implementation defines a Calculator class that contains methods for each operation.

The functional implementation is simpler and easier to understand for beginners, as it uses familiar function definitions to perform the operations. On the other hand, the OOP implementation provides a more organized and modular approach, as all the operations are encapsulated within a single class. This makes it easier to maintain and extend the code in the future.

Example #2: Bank Account

Using Function

def deposit(balance, amount):
    return balance + amount

def withdraw(balance, amount):
    if balance < amount:
        raise ValueError("Insufficient balance!")
    return balance - amount

Using OOP

class BankAccount:
    def __init__(self, balance):
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        if self.balance < amount:
            raise ValueError("Insufficient balance!")
        self.balance -= amount

Explanation: The above programs implement a simple bank account that allows for deposits and withdrawals. The functional implementation defines deposit and withdraws functions that take the current balance and the amount to be deposited or withdrawn as input.

The OOP implementation defines a BankAccount class that contains attributes for the current balance and methods for depositing and withdrawing money. The init method is used to initialize the initial balance when a new BankAccount object is created.

The OOP implementation provides a more realistic representation of a bank account, as it encapsulates the balance and operations within a single class. This makes it easier to maintain and extend the code in the future, as well as to keep track of multiple bank accounts at once.

Example #3: To-Do List

Using Function

def add_task(tasks, task):
    tasks.append(task)

def remove_task(tasks, task):
    tasks.remove(task)

Using OOP

class TodoList:
    def __init__(self):
        self.tasks = []

    def add_task(self, task):
        self.tasks.append(task)

    def remove_task(self, task):
        self.tasks.remove(task)

Explanation: The above programs implement a simple to-do list that allows for adding and removing tasks. The functional implementation defines add_task and remove_task functions that take a list of tasks and the task to be added or removed as input.

The OOP implementation defines a TodoList class that contains an attribute for the list of tasks and methods for adding and removing tasks. The init method is used to initialize an empty list of tasks when a new TodoList object is created.

The OOP implementation provides a more organized and modular approach, as all the tasks and operations are encapsulated within a single class. This makes it easier to maintain and extend the code in the future, as well as to keep track of multiple to-do lists at once.

Overall, while both functional programming and OOP can be used to solve the same problems, OOP provides a more organized and modular approach, especially for larger and more complex programs. OOP allows for encapsulation, inheritance, and polymorphism, which can help to reduce code duplication, improve code maintainability, and make the code more extensible. However, for smaller and simpler programs, functional programming may be more suitable, as it is simpler and easier to understand for beginners.

In the next article “Mastering Object-Oriented Programming (OOP) in Python in Three Simple Ways — Part 2”, we will discuss and practice creating class diagram design, so you can get a clear and better understanding of OOP.

See you in the next article!


메타데이터
post_id
3f5b281f4b53
slug
mastering-object-oriented-programming-oop-in-python-in-three-simple-ways-part-1-oop-3f5b281f4b53
url
https://medium.com/@hasan40p30m/mastering-object-oriented-programming-oop-in-python-in-three-simple-ways-part-1-oop-3f5b281f4b53
canonical_url
https://medium.com/@hasan40p30m/mastering-object-oriented-programming-oop-in-python-in-three-simple-ways-part-1-oop-3f5b281f4b53
author_url
https://medium.com/@hasan40p30m
status
ok
fetched_at
2026-07-25 21:41:35