OOPs concept in Python With Examples

Four Pillars of OOP in Python

Exploring the Four Pillars of OOP in Python

1. Encapsulation

Encapsulation bundles data and methods into a class, providing better control and security.


class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def get_salary(self):
        return self.salary

    def set_salary(self, new_salary):
        if new_salary > 0:
            self.salary = new_salary

emp = Employee("John", 50000)
print(emp.get_salary())
    

2. Abstraction

Abstraction simplifies complex implementations by providing a clear interface.


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.14159 * self.radius ** 2

circle = Circle(5)
print("Circle Area:", circle.area())
    

3. Inheritance

Inheritance allows creating new classes based on existing ones, promoting code reusability.


class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

dog = Dog()
cat = Cat()
print(dog.speak())
print(cat.speak())
    

4. Polymorphism

Polymorphism enables different objects to be treated uniformly, offering flexibility.


class Bird:
    def make_sound(self):
        pass

class Sparrow(Bird):
    def make_sound(self):
        return "Chirp!"

class Parrot(Bird):
    def make_sound(self):
        return "Squawk!"

def animal_sound(bird):
    return bird.make_sound()

sparrow = Sparrow()
parrot = Parrot()
print(animal_sound(sparrow))
print(animal_sound(parrot))
    

It shows static keyword usage


class Example:
    static_variable = 0  # Static variable
    
    def __init__(self, value):
        self.value = value  # Instance variable
    
    @staticmethod
    def static_method():
        print("This is a static method.")
    
    def instance_method(self):
        print("This is an instance method. Value:", self.value)
    
# Accessing static variable directly
print("Accessing static variable directly:", Example.static_variable)  # Output: Accessing static variable directly: 0

# Modifying static variable
Example.static_variable = 42

# Creating instances
obj1 = Example(10)
obj2 = Example(20)

# Accessing instance variables and methods
obj1.instance_method()  # Output: This is an instance method. Value: 10
obj2.instance_method()  # Output: This is an instance method. Value: 20

# Accessing static method
Example.static_method()  # Output: This is a static method.

# Accessing modified static variable through class
print("Accessing modified static variable through class:", Example.static_variable)  # Output: Accessing modified static variable through class: 42

# Accessing modified static variable through instance
print("Accessing modified static variable through instance:", obj1.static_variable)    # Output: Accessing modified static variable through instance: 42


    

Now lets see a program that shows all the major concepts of OOP using python


from abc import ABC, abstractmethod

class Vehicle(ABC):
    def __init__(self, make, model):
        self._make = make   # Protected attribute
        self._model = model # Protected attribute
    
    @abstractmethod
    def start(self):
        pass

class Car(Vehicle):
    def start(self):
        return f"{self._make} {self._model} engine started"  # Accessing protected attributes

class Bike(Vehicle):
    def start(self):
        return f"{self._make} {self._model} engine started"  # Accessing protected attributes

def engine_start(vehicle):
    return vehicle.start()

car = Car("Toyota", "Camry")
bike = Bike("Honda", "CBR")

print(engine_start(car))
print(engine_start(bike))

    

It shows the bank Account operations


class BankAccount:
    def __init__(self, account_number, password, initial_balance=0):
        self.account_number = account_number
        self.password = password
        self.balance = initial_balance

    def check_balance(self):
        return self.balance

    def add_money(self, amount):
        self.balance += amount
        return f"Added ${amount}. New balance: ${self.balance}"

    def credit(self, amount, password):
        if password == self.password:
            self.balance += amount
            return f"Amount ${amount} credited. New balance: ${self.balance}"
        else:
            return "Incorrect password. Credit operation denied."

    def debit(self, amount, password):
        if password == self.password:
            if self.balance >= amount:
                self.balance -= amount
                return f"Withdrew ${amount}. New balance: ${self.balance}"
            else:
                return "Insufficient funds"
        else:
            return "Incorrect password. Debit operation denied."

# Creating an instance of BankAccount
account = BankAccount("123456", "mypassword", 1000)

# Checking balance
print("Balance:", account.check_balance())

# Adding money
print(account.add_money(500))

# Crediting with password
print(account.credit(200, "mypassword"))  # Correct password
print(account.credit(300, "wrongpassword"))  # Incorrect password

# Debiting with password
print(account.debit(400, "mypassword"))  # Correct password
print(account.debit(800, "wrongpassword"))  # Incorrect password



    


Click this for OOPs in Python

Click this for Exception Handling

Click this for File Handling


Comments