OOPs principles
Code with Detailed Comments:
# Object-Oriented Programming (OOP) Concepts in Python
# 1. Class and Object
class Animal:
"""A base class to represent an animal"""
def __init__(self, name, species):
self.name = name # Public Attribute
self.species = species # Public Attribute
def make_sound(self):
"""A general method to make a sound"""
return "Some generic sound"
def __str__(self):
"""Magic Method to return a string representation"""
return f"{self.name} is a {self.species}"
# 2. Encapsulation: Protecting data using private attributes
class BankAccount:
"""A class to demonstrate Encapsulation"""
def __init__(self, account_holder, balance):
self.account_holder = account_holder # Public attribute
self.__balance = balance # Private attribute (Encapsulation)
def deposit(self, amount):
"""Public method to deposit money"""
if amount > 0:
self.__balance += amount
return f"Deposited {amount}, New Balance: {self.__balance}"
return "Invalid deposit amount"
def withdraw(self, amount):
"""Public method to withdraw money"""
if 0 < amount <= self.__balance:
self.__balance -= amount
return f"Withdrew {amount}, Remaining Balance: {self.__balance}"
return "Insufficient funds"
def get_balance(self):
"""Getter method to access private attribute"""
return self.__balance
# 3. Abstraction: Hiding complex details and exposing only necessary parts
from abc import ABC, abstractmethod
class Vehicle(ABC):
"""Abstract class that forces subclasses to implement specific methods"""
@abstractmethod
def start_engine(self):
pass
@abstractmethod
def stop_engine(self):
pass
class Car(Vehicle):
"""Concrete class implementing the abstract methods"""
def start_engine(self):
return "Car engine started"
def stop_engine(self):
return "Car engine stopped"
# 4. Inheritance (IS-A Relationship): Creating a hierarchy
class Dog(Animal):
"""Dog IS-A Animal (Inheritance)"""
def __init__(self, name, breed):
super().__init__(name, "Dog") # Calling parent class constructor
self.breed = breed # Additional attribute
def make_sound(self):
"""Method Overriding (Polymorphism)"""
return "Bark!"
class Cat(Animal):
"""Cat IS-A Animal"""
def __init__(self, name, color):
super().__init__(name, "Cat")
self.color = color
def make_sound(self):
return "Meow!"
# 5. Multiple Inheritance
class Flying:
"""A class to add flying capability"""
def fly(self):
return "I can fly!"
class Bird(Animal, Flying):
"""Bird IS-A Animal and it also CAN Fly"""
def __init__(self, name, species):
super().__init__(name, species)
def make_sound(self):
return "Chirp!"
# 6. Multilevel Inheritance
class Puppy(Dog):
"""Puppy IS-A Dog, which IS-A Animal"""
def __init__(self, name, breed, age):
super().__init__(name, breed)
self.age = age
def is_cute(self):
return f"{self.name} is a cute {self.age}-month-old puppy!"
# 7. Hierarchical Inheritance: Multiple child classes from the same base
class Lion(Animal):
"""Lion IS-A Animal"""
def __init__(self, name):
super().__init__(name, "Lion")
def make_sound(self):
return "Roar!"
# 8. Polymorphism: Method Overriding
def animal_sound(animal):
"""Function to demonstrate polymorphism"""
return animal.make_sound()
# 9. Method Overloading (Using Default Arguments)
class MathOperations:
"""Demonstrating method overloading"""
def add(self, a, b, c=0):
return a + b + c
# 10. Static Methods and Class Methods
class Utility:
"""A class with static and class methods"""
@staticmethod
def greet():
return "Hello, welcome to OOP in Python!"
@classmethod
def describe_class(cls):
return f"This is {cls.__name__} class."
# 11. Composition (HAS-A Relationship)
class Engine:
"""Engine class"""
def start(self):
return "Engine started"
def stop(self):
return "Engine stopped"
class CarWithEngine:
"""Car HAS-A Engine (Composition)"""
def __init__(self, model):
self.model = model
self.engine = Engine() # Composition
def start_car(self):
return f"{self.model}: {self.engine.start()}"
def stop_car(self):
return f"{self.model}: {self.engine.stop()}"
# Demonstration of OOP concepts
if __name__ == "__main__":
# Creating Objects
dog = Dog("Buddy", "Golden Retriever")
cat = Cat("Whiskers", "Black")
lion = Lion("Simba")
# Demonstrate Polymorphism
print(animal_sound(dog)) # Output: Bark!
print(animal_sound(cat)) # Output: Meow!
print(animal_sound(lion)) # Output: Roar!
# Demonstrate Encapsulation
account = BankAccount("Alice", 1000)
print(account.deposit(500))
print(account.withdraw(300))
print(f"Balance: {account.get_balance()}")
# Demonstrate Abstraction
car = Car()
print(car.start_engine())
print(car.stop_engine())
# Demonstrate Composition
my_car = CarWithEngine("Tesla Model X")
print(my_car.start_car())
print(my_car.stop_car())
# Demonstrate Multiple Inheritance
bird = Bird("Eagle", "Bird of Prey")
print(bird.fly()) # Output: I can fly!
# Demonstrate Static and Class Methods
print(Utility.greet()) # Output: Hello, welcome to OOP in Python!
print(Utility.describe_class()) # Output: This is Utility class.
# Demonstrate Multilevel Inheritance
puppy = Puppy("Max", "Labrador", 3)
print(puppy.is_cute())
# Demonstrate Method Overloading
math_ops = MathOperations()
print(math_ops.add(5, 10)) # Output: 15
print(math_ops.add(5, 10, 20)) # Output: 35Summary of OOP Concepts Demonstrated:
Key OOP Concepts Covered:
🔹 Python Code with Detailed Comments:
Last updated