Object-Oriented Programming (OOP)
Object-Oriented Programming is a paradigm that uses objects and classes to structure and organize code. Below are the fundamental concepts of OOP with examples:
1. Class and Object
- Class: A blueprint for creating objects.
- Object: An instance of a class, with its own data and behavior.
class Car:
def __init__(self, brand, speed):
self.brand = brand
self.speed = speed
def drive(self):
return f"{self.brand} is driving at {self.speed} km/h."
# Main
car1 = Car("Toyota", 120)
print(car1.drive())
---------------------------------------
Toyota is driving at 120 km/h.
2. Encapsulation
- Encapsulation bundles data and methods together, restricting access using private attributes.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
# Main
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance())
---------------------------------------
1500
3. Inheritance
- Inheritance enables a class (child) to reuse the properties and methods of another class (parent).
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
class Dog(Animal):
def speak(self):
return f"{self.name} barks."
# Main
dog = Dog("Buddy")
print(dog.speak())
---------------------------------------
Buddy barks.
4. Polymorphism
- Polymorphism allows methods in different classes to have the same name but different behaviors.
class Bird:
def fly(self):
return "Birds can fly."
class Penguin(Bird):
def fly(self):
return "Penguins cannot fly."
# Main
animals = [Bird(), Penguin()]
for animal in animals:
print(animal.fly())
---------------------------------------
Birds can fly.
Penguins cannot fly.