You are on page 1of 5

inheritance

# Define the parent class


class Animal:
def __init__(self, name):
self.name = name

def make_sound(self):
pass

# Define the child class


class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed

def make_sound(self):
print("Woof!")

# Create an instance of the child class


my_dog = Dog("Buddy", "Labrador")

# Print the name and breed of the dog


print(f"My dog's name is {my_dog.name} and it is a {my_dog.breed}.")

# Call the make_sound method


my_dog.make_sound()

My dog's name is Buddy and it is a Labrador.


Woof!

types

1 Single Inheritance

class Parent:
def func_parent(self):
print("This function is in parent class.")

class Child(Parent):
def func_child(self):
print("This function is in child class.")

obj = Child()
obj.func_parent()
obj.func_child()

This function is in parent class.


This function is in child class.

2 Multiple Inheritance

class Parent1:
def func_parent1(self):
print("This function is in parent1 class.")

class Parent2:
def func_parent2(self):
print("This function is in parent2 class.")

class Child(Parent1, Parent2):


pass

obj = Child()
obj.func_parent1()
obj.func_parent2()

This function is in parent1 class.


This function is in parent2 class.

3 Multilevel Inheritance

class Parent:
def func_parent(self):
print("This function is in parent class.")

class Child1(Parent):
def func_child1(self):
print("This function is in child1 class.")

class Child2(Child1):
pass

obj = Child2()
obj.func_parent()
obj.func_child1()

This function is in parent class.


This function is in child1 class.

4 Hierarchical Inheritance

class Parent:
def func_parent(self):
print("This function is in parent class.")

class Child1(Parent):
pass

class Child2(Parent):
pass

obj1 = Child1()
obj2 = Child2()

obj1.func_parent()
obj2.func_parent()

This function is in parent class.


This function is in parent class.

polymorphism

class Animal:
def speak(self):
print("I am an animal")

class Dog(Animal):
def speak(self):
print("I am a dog")

animal = Animal()
dog = Dog()

animal.speak()
dog.speak()

I am an animal
I am a dog

encapsulation

class BankAccount:
def __init__(self, balance=0):
self.__balance = balance # private attribute

def deposit(self, amount):


self.__balance += amount
return self.__balance

def withdraw(self, amount):


if amount > self.__balance:
print("Insufficient balance")
return None
else:
self.__balance -= amount
return self.__balance

def get_balance(self):
return self.__balance

# create a new bank account with a balance of 1000


account = BankAccount(1000)

# deposit 500
print("Depositing 500: ", account.deposit(500))

# withdraw 200
print("Withdrawing 200: ", account.withdraw(200))

# withdraw 1500
print("Withdrawing 1500: ", account.withdraw(1500))

# get the current balance


print("Current balance: ", account.get_balance())

Depositing 500: 1500


Withdrawing 200: 1300
Withdrawing 1500: Insufficient balance
None
Current balance: 1300

data abstraction

from abc import ABC, abstractmethod

class Shape(ABC):
@abstractmethod
def area(self):
pass

class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height

def area(self):
return self.width * self.height

class Circle(Shape):
def __init__(self, radius):
self.radius = radius

def area(self):
return 3.14 * self.radius ** 2

# create a new rectangle with a width of 10 and a height of 5


rectangle = Rectangle(10, 5)

# calculate the area of the rectangle


print("Rectangle area: ", rectangle.area())

# create a new circle with a radius of 3


circle = Circle(3)

# calculate the area of the circle


print("Circle area: ", circle.area())
Rectangle area: 50
Circle area: 28.26

error handling

try:
# try to convert a string to an integer
number = int("hello")
except ValueError:
# handle the ValueError exception
print("Error: invalid number")

try:
# try to divide by zero
result = 10 / 0
except ZeroDivisionError:
# handle the ZeroDivisionError exception
print("Error: cannot divide by zero")

try:
# try to open a non-existent file
with open("nonexistentfile.txt", "r") as file:
content = file.read()
except FileNotFoundError:
# handle the FileNotFoundError exception
print("Error: file not found")

try:
# try to access an index that does not exist in a list
numbers = [1, 2, 3]
print(numbers[5])
except IndexError:
# handle the IndexError exception
print("Error: index out of range")

Error: invalid number


Error: cannot divide by zero
Error: file not found
Error: index out of range

all exception handling

You might also like