OOP (Object Oriented Programming) is a programming paradigm that uses objects and classes to structure code. It allows for encapsulation, inheritance, and polymorphism, making it easier to manage complex software systems.
# 0. Class Definition
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"Hi, I'm {self.name} and I'm {self.age} years old"
def have_birthday(self):
self.age += 1
# Create objects
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
print(person1.introduce())
person1.have_birthday()
print(f"After birthday: {person1.age}")Hi, I'm Alice and I'm 25 years old
After birthday: 26
# 1. Class and Object
class Animal:
def __init__(self, name):
self.name = name # Attribute
def speak(self): # Method
return f"{self.name} makes a sound."
# Create an object
dog = Animal("Dog")
print(dog.speak())Dog makes a sound.
# 2. Inheritance
class Dog(Animal):
def speak(self): # Override the method
return f"{self.name} barks."
my_dog = Dog("Buddy")
print(my_dog.speak())Buddy barks.
# 3. 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
account = BankAccount(100)
account.deposit(50)
print(account.get_balance())150
# 4. Polymorphism
class Cat(Animal):
def speak(self):
return f"{self.name} meows."
animals = [Dog("Rex"), Cat("Whiskers")]
for animal in animals:
print(animal.speak())Rex barks.
Whiskers meows.
# 5. Abstraction
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def drive(self):
pass
class Car(Vehicle):
def drive(self):
return "Car is driving"
car = Car()
print(car.drive())Car is driving
# 6. Class vs Instance Attributes
class Counter:
count = 0 # Class attribute
def __init__(self):
Counter.count += 1
print(Counter.count)
c1 = Counter()
c2 = Counter()
print(Counter.count)0
2
# 7. Static and Class Methods
class MathUtils:
var = "MathUtils"
@staticmethod
def add(a, b):
return a + b
@classmethod
def description(cls):
return f"This is a math utility class: {cls.var}"
print(MathUtils.add(2, 3))
print(MathUtils.description())5
This is a math utility class: MathUtils