Professional Documents
Culture Documents
def make_sound(self):
pass
def make_sound(self):
print("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()
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.")
obj = Child()
obj.func_parent1()
obj.func_parent2()
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()
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()
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 get_balance(self):
return self.__balance
# deposit 500
print("Depositing 500: ", account.deposit(500))
# withdraw 200
print("Withdrawing 200: ", account.withdraw(200))
# withdraw 1500
print("Withdrawing 1500: ", account.withdraw(1500))
data abstraction
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
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")