Obafemi Emmanuel

Object-Oriented Programming (OOP) in Python

Published 1 month ago

Object-Oriented Programming (OOP) is a fundamental programming paradigm that focuses on organizing code using objects and classes. Python is an excellent language for OOP, as it provides robust support for encapsulation, inheritance, polymorphism, and abstraction. In this blog, we will explore these core concepts of OOP in Python.


1. Classes and Objects

What are Classes and Objects?

A class is a blueprint for creating objects. It defines properties (attributes) and behaviors (methods) that objects instantiated from the class will have. An object is an instance of a class.


Creating a Class and an Object

class Car:
    def __init__(self, brand, model, year):
        self.brand = brand
        self.model = model
        self.year = year
    
    def display_info(self):
        return f"{self.year} {self.brand} {self.model}"

# Creating an object of the Car class
my_car = Car("Toyota", "Corolla", 2022)
print(my_car.display_info())  # Output: 2022 Toyota Corolla

2. Inheritance and Polymorphism

Inheritance

Inheritance allows a class (child) to inherit attributes and methods from another class (parent), enabling code reuse and hierarchy representation.

class Vehicle:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model
    
    def display_info(self):
        return f"Vehicle: {self.brand} {self.model}"

# Child class inheriting from Vehicle
class Car(Vehicle):
    def __init__(self, brand, model, year):
        super().__init__(brand, model)
        self.year = year
    
    def display_info(self):
        return f"Car: {self.year} {self.brand} {self.model}"

# Creating an instance
my_car = Car("Honda", "Civic", 2023)
print(my_car.display_info())  # Output: Car: 2023 Honda Civic

Polymorphism

Polymorphism allows different classes to define methods with the same name, enabling a common interface for different object types.

class Dog:
    def sound(self):
        return "Bark"

class Cat:
    def sound(self):
        return "Meow"

# Using polymorphism
animals = [Dog(), Cat()]
for animal in animals:
    print(animal.sound())  # Output: Bark Meow

3. Encapsulation and Abstraction

Encapsulation

Encapsulation restricts direct access to an object’s data and allows modification only through defined methods.

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # Private variable
    
    def deposit(self, amount):
        self.__balance += amount
    
    def get_balance(self):
        return self.__balance

account = BankAccount(1000)
account.deposit(500)
print(account.get_balance())  # Output: 1500

Abstraction

Abstraction hides complex implementation details and exposes only necessary functionalities.

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
    
    def area(self):
        return 3.14 * self.radius * self.radius

circle = Circle(5)
print(circle.area())  # Output: 78.5

4. Magic Methods

Magic methods (also known as dunder methods) are special methods with double underscores (__) that allow objects to behave like built-in types.


Common Magic Methods

  • __init__: Constructor method
  • __str__: Returns a string representation
  • __len__: Returns the length of an object
  • __add__: Defines behavior for the + operator
class Book:
    def __init__(self, title, pages):
        self.title = title
        self.pages = pages
    
    def __str__(self):
        return f"Book: {self.title}, Pages: {self.pages}"
    
    def __len__(self):
        return self.pages

book = Book("Python Programming", 450)
print(book)        # Output: Book: Python Programming, Pages: 450
print(len(book))   # Output: 450

Overloading Operators

Magic methods allow operator overloading, letting objects behave naturally with operators.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)
    
    def __str__(self):
        return f"({self.x}, {self.y})"

p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3)  # Output: (4, 6)

Conclusion

Object-Oriented Programming (OOP) in Python helps in building scalable, reusable, and well-structured code. Understanding classes, objects, inheritance, polymorphism, encapsulation, abstraction, and magic methods allows developers to write more efficient and maintainable programs. By leveraging these OOP principles, Python developers can build complex applications with greater ease.


Leave a Comment


Choose Colour