OOPS
OOPS
class Car:
def __init__(self, brand, model): # Constructor method
self.brand = brand
self.model = model
def display_info(self):
print(f"Car: {self.brand} {self.model}")
class Animal:
def speak(self):
print("Animals make sounds")
class Dog(Animal):
def speak(self): # Overriding the parent method
print("Dogs bark")
d = Dog()
d.speak()
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private variable
def get_balance(self):
return self.__balance # Access through method
account = BankAccount(1000)
print(account.get_balance()) # Output: 1000
print(account.__balance) # ❌ Error: Private variable
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
c = Circle(5)
print(c.area()) # Output: 78.5
Example: Inheritance
Python
class Parent:
def show(self):
print("This is the parent class")
class Child(Parent):
pass # Inherits everything from Parent
c = Child()
c.show() # Output: This is the parent class
Example: Composition
Python
class Engine:
def start(self):
print("Engine starting...")
class Car:
def __init__(self):
self.engine = Engine() # Composition
def start_car(self):
self.engine.start()
my_car = Car()
my_car.start_car() # Output: Engine starting...
class Vehicle:
def move(self):
print("Vehicle is moving")
class Bicycle(Vehicle):
def move(self): # Specialization of inherited method
print("Bicycle is pedaling")
bike = Bicycle()
bike.move() # Output: Bicycle is pedaling
Key Takeaways
✔ Classes define object structure.
✔ Overriding lets subclasses modify behavior.
✔ Encapsulation hides sensitive data.
✔ Abstraction simplifies interfaces.
✔ Inheritance and composition allow code reuse.
✔ Specialization refines inherited methods.