Navigation

Class and Object Encapsulation Inheritance Polymorphism

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 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

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

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

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.