Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
12 views34 pages

Python OOPS Concept

The document explains key concepts in object-oriented programming: encapsulation, inheritance, and polymorphism, along with exception handling. It provides definitions, code examples, and explanations for each concept, including the use of try-except blocks and custom exceptions. Additionally, it illustrates how to handle errors and manage program flow during execution.

Uploaded by

Alex Any
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views34 pages

Python OOPS Concept

The document explains key concepts in object-oriented programming: encapsulation, inheritance, and polymorphism, along with exception handling. It provides definitions, code examples, and explanations for each concept, including the use of try-except blocks and custom exceptions. Additionally, it illustrates how to handle errors and manage program flow during execution.

Uploaded by

Alex Any
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

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)

You might also like