Encapsulation
Definition:
•Hiding internal details of objects
•Using private variables (prefix _ or __)
class BankAccount:
def __init__(self):
self.__balance = 0
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount()
account.deposit(100)
print(account.get_balance()) # Output: 100
Inheritance
Definition:
•One class (child) inherits from another (parent)
class Vehicle:
def move(self):
print("Vehicle is moving")
class Car(Vehicle):
def honk(self):
print("Car is honking")
my_car = Car()
my_car.move()
my_car.honk()
Explanation:
•Car inherits move() from Vehicle
•Adds new behavior: honk()
Polymorphism
Definition:
•Same method name, different behaviours
class Animal:
def speak(self):
print("Some sound")
class Dog(Animal):
def speak(self):
print("Woof!")
class Cat(Animal):
def speak(self):
print("Meow!")
for pet in [Dog(), Cat()]:
pet.speak()
Explanation:
•speak() behaves differently based on the object
What is an Exception?
•Definition: An error that occurs during program execution and disrupts the normal flow.
•Examples:
•Division by zero (ZeroDivisionError)
•File not found (FileNotFoundError)
•Invalid type (TypeError)
The try-except Block
try:
# Code that may raise an exception
except ExceptionType:
# Code that runs if exception occurs
Multiple except Blocks
try:
num = int(input("Enter number: "))
result = 10 / num
except ValueError:
print("Invalid input!")
except ZeroDivisionError:
print("Division by zero!")
Using else and finally
try:
x = int(input("Enter number: "))
print(10 / x)
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful.")
finally:
print("This block always executes.")
•else: Runs if no exception occurs
•finally: Runs regardless of exception
Raising Exceptions
Use raise to trigger exceptions manually.
def set_age(age):
if age < 0:
raise ValueError("Age cannot be
negative")
print(f"Age set to {age}")
Custom Exceptions
Create your own exception classes:
class MyError(Exception):
pass
try:
raise MyError("Something went wrong")
except MyError as e:
print(e)