Python OOP Concepts with Examples

Introduction

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects, which can contain data in the form of attributes (fields or properties) and code in the form of methods (functions). Python is an object-oriented programming language that allows you to create and manipulate objects. This tutorial covers the main OOP concepts in Python, including classes, objects, inheritance, polymorphism, encapsulation, and abstraction.

Table of Contents

  1. Classes and Objects
  2. Inheritance
  3. Polymorphism
  4. Encapsulation
  5. Abstraction

1. Classes and Objects

Class

A class is a blueprint for creating objects. It defines a set of attributes and methods that the created objects will have.

Example

class Car:
    def __init__(self, brand, model, year):
        self.brand = brand
        self.model = model
        self.year = year

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

# Creating objects of the Car class
car1 = Car("Toyota", "Corolla", 2020)
car2 = Car("Honda", "Civic", 2019)

# Using the display_info method
print(car1.display_info())  # Output: Car: Toyota Corolla, Year: 2020
print(car2.display_info())  # Output: Car: Honda Civic, Year: 2019

2. Inheritance

Inheritance is a way to create a new class that is based on an existing class. The new class (child class) inherits attributes and methods from the existing class (parent class).

Example

class Vehicle:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def display_info(self):
        return f"Vehicle: {self.brand} {self.model}"

class Car(Vehicle):
    def __init__(self, brand, model, year):
        super().__init__(brand, model)
        self.year = year

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

# Creating an object of the Car class
car = Car("Tesla", "Model S", 2022)

# Using the display_info method
print(car.display_info())  # Output: Car: Tesla Model S, Year: 2022

3. Polymorphism

Polymorphism allows methods to be used interchangeably between different classes. It allows the same method to be defined in different classes, with each class having its own implementation.

Example

class Bird:
    def make_sound(self):
        return "Tweet"

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

def animal_sound(animal):
    print(animal.make_sound())

# Creating objects of Bird and Dog classes
bird = Bird()
dog = Dog()

# Using the animal_sound function
animal_sound(bird)  # Output: Tweet
animal_sound(dog)   # Output: Bark

4. Encapsulation

Encapsulation is the practice of hiding the internal state and functionality of an object and only exposing a limited interface. This is usually done by making attributes private (prefixing them with an underscore) and providing public methods to access and modify them.

Example

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.__balance = balance  # Private attribute

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
        else:
            print("Deposit amount must be positive")

    def withdraw(self, amount):
        if amount <= self.__balance:
            self.__balance -= amount
        else:
            print("Insufficient funds")

    def get_balance(self):
        return self.__balance

# Creating an object of the BankAccount class
account = BankAccount("Ravi", 1000)

# Using public methods to interact with the private attribute
account.deposit(500)
print(account.get_balance())  # Output: 1500

account.withdraw(200)
print(account.get_balance())  # Output: 1300

# Attempting to access the private attribute directly (will raise an AttributeError)
# print(account.__balance)  # AttributeError: 'BankAccount' object has no attribute '__balance'

5. Abstraction

Abstraction is the concept of hiding the complex implementation details and showing only the essential features of an object. This can be achieved using abstract classes and methods.

Example

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        return "Bark"

class Cat(Animal):
    def make_sound(self):
        return "Meow"

# Creating objects of Dog and Cat classes
dog = Dog()
cat = Cat()

# Using the make_sound method
print(dog.make_sound())  # Output: Bark
print(cat.make_sound())  # Output: Meow

Conclusion

Object-Oriented Programming (OOP) in Python provides a powerful and flexible way to organize and manage code. By understanding and utilizing concepts such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction, you can design and implement more robust and maintainable software. This tutorial covered the main OOP concepts in Python with examples to help you get started with OOP in Python.

Comments