1) Objects and classes
# Define a class
class Student:
# Method to display student details
def show_details(self, name, age):
print("Name:", name)
print("Age:", age)
# Create an object
student1 = Student()
student2 = Student()
# Call the method and pass values
student1.show_details("Alice", 20)
print()
student2.show_details("Bob", 22)
2) Single inheritance
# Parent class
class Animal:
def sound(self):
print("Animal makes sound")
# Child class
class Dog(Animal):
def bark(self):
print("Dog barks")
# Create object
d = Dog()
[Link]()
[Link]()
3) Multilevel inheritance
# Grandparent class
class Animal:
def sound(self):
print("Animal makes sound")
# Parent class
class Dog(Animal):
def bark(self):
print("Dog barks")
# Child class
class Puppy(Dog):
def cute(self):
print("Puppy is cute!")
# Create object
p = Puppy()
[Link]()
[Link]()
[Link]()
4) Multiple inheritance
# First parent class
class Father:
def gardening(self):
print("Father loves gardening.")
# Second parent class
class Mother:
def cooking(self):
print("Mother loves cooking.")
# Child class inherits from both
class Child(Father, Mother):
def sports(self):
print("Child loves sports.")
# Create object
c = Child()
[Link]()
[Link]()
[Link]()
5) Method overriding
# Parent class
class Animal:
def sound(self):
print("Animal makes some sound")
# Child class
class Dog(Animal):
def sound(self):
print("Dog barks: Woof Woof!")
# Create objects
a = Animal()
d = Dog()
# Call the methods
[Link]() # Calls parent class method
[Link]() # Calls child class method (overrides parent method)
6) Method overloading
class Calculator:
def add(self, a=0, b=0, c=0):
print("Sum:", a + b + c)
# Create object
calc = Calculator()
# Call the method with different numbers of arguments
[Link](2, 3) # Only two numbers
[Link](1, 4, 5) # Three numbers
[Link]() # No numbers (uses all default 0)
7) polymorphism
class Dog:
def sound(self):
print("Dog barks: Woof Woof!")
class Cat:
def sound(self):
print("Cat meows: Meow Meow!")
# Common function
def animal_sound(animal):
[Link]()
# Create objects
dog = Dog()
cat = Cat()
# Call the function with different objects
animal_sound(dog)
animal_sound(cat)
8) Operator overloading
class Student:
def __init__(self, marks):
[Link] = marks
# Overloading the + operator
def __add__(self, other):
return [Link] + [Link]
# Create two student objects
s1 = Student(85)
s2 = Student(90)
# Add objects
total = s1 + s2
print("Total Marks:", total)
9) Abstract class
from abc import ABC, abstractmethod
# Abstract Class
class Animal(ABC):
@abstractmethod
def sound(self):
pass
# Subclass must implement sound()
class Dog(Animal):
def sound(self):
print("Dog barks")
# Create object
d = Dog()
[Link]()
10)Abstract method
from abc import ABC, abstractmethod
# Abstract class with an abstract method
class Animal(ABC):
@abstractmethod
def sound(self):
pass
# Child class that implements the abstract method
class Dog(Animal):
def sound(self):
print("Dog barks: Woof Woof!")
# Child class that implements the abstract method
class Cat(Animal):
def sound(self):
print("Cat meows: Meow Meow!")
# Create objects
dog = Dog()
cat = Cat()
# Call the implemented methods
[Link]()
[Link]()
11)Interfaces
from abc import ABC, abstractmethod
# Interface
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
@abstractmethod
def stop(self):
pass
# Class implementing the interface
class Car(Vehicle):
def start(self):
print("Car started")
def stop(self):
print("Car stopped")
# Create object
c = Car()
[Link]()
[Link]()
12)Threads
import threading
import time
# Function for thread 1
def print_numbers():
for i in range(1, 6):
print(f"Number: {i}")
[Link](1)
# Function for thread 2
def print_letters():
for letter in ['A', 'B', 'C', 'D', 'E']:
print(f"Letter: {letter}")
[Link](1)
# Function for thread 3 (demonstrating thread synchronization with Lock)
def print_synced():
[Link]() # Lock acquired
for i in range(1, 4):
print(f"Synced Print: {i}")
[Link](0.5)
[Link]() # Lock released
# Create Lock for synchronization
lock = [Link]()
# Create threads
thread1 = [Link](target=print_numbers)
thread2 = [Link](target=print_letters)
thread3 = [Link](target=print_synced)
# Start the threads
[Link]()
[Link]()
[Link]()
# Join threads to wait for them to finish
[Link]()
[Link]()
[Link]()
print("All threads have finished!")
13)Exception handling
# Function that might cause different exceptions
def risky_function(a, b):
try:
# Possible ZeroDivisionError
result = a / b
print("Result:", result)
# Possible ValueError
int_value = int(input("Enter an integer: "))
print("Integer Value:", int_value)
# IndexError if list is empty or out of range
my_list = [1, 2, 3]
print(my_list[5]) # Will raise IndexError
except ZeroDivisionError as e:
print("Error: Cannot divide by zero!", e)
except ValueError as e:
print("Error: Invalid input. Please enter a number.", e)
except IndexError as e:
print("Error: Index out of range.", e)
# Catching general exceptions (for unexpected errors)
except Exception as e:
print("An unexpected error occurred:", e)
else:
print("No exceptions occurred. All operations were successful.")
finally:
print("Finally block: This always runs, no matter what!")
# Call the function
risky_function(10, 0) # Will cause ZeroDivisionError