Day 6 - Python Lect 5
Day 6 - Python Lect 5
Language
MICROSOFT AI-102 COURSE
DAY 7
PYTHON LECT # 6
1
Agenda
Exception Handling
OOP
• Class & Object
• Instance Variables & Methods
• Class Variables & Functions
• Constructors & Destructors
• Inheritance
• Multilevel Inheritance
2
Agenda
• Hierarchical Inheritance
• Multiple Inheritance
• Method Resolution Order
• Access Specifiers: Private, Public, Protected
3
Exception Handling
Exception handling is a mechanism to handle errors gracefully during the execution of
a program. It helps in managing unexpected conditions and ensures the program can
handle errors without crashing.
Exceptions: An exception is an event that occurs during the execution of a program
that disrupts its normal flow. Examples include ZeroDivisionError, FileNotFoundError,
TypeError, etc.
Try Block: The code that might raise an exception is placed inside the try block. Except
Block: The code to handle the exception is placed inside the except block. You can
specify different types of exceptions to handle various errors differently.
Else Block: The code inside the else block executes if the try block does not raise an
exception.
Finally Block: The code inside the finally block always executes, regardless of whether
an exception was raised or not. It is typically used for cleanup actions. 4
Exmp
try:
with open('file.txt', 'r') as file:
content = file.read()
except FileNotFoundError as e:
print(f"Error: {e}")
else:
print("File read successfully.")
finally:
print("This will always be executed.")
5
Multiple Exception
try:
# Some risky code
result = 10 / z
except ZeroDivisionError:
print("Cannot divide by zero.")
except TypeError:
print("Type error occurred.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
else:
print("No Error here .")
finally:
print("This will always be executed.") 6
Object Oriented Programming
OOP is a programming paradigm that revolves around the concept of objects.
These objects are like real-world entities with their own properties (data) and
behaviors (functions).
Class: A blueprint or template for creating objects. It defines the properties
and methods that objects of that class will have.
Object: An instance of a class. It has its own data values (attributes) and can
perform actions (methods).
Encapsulation: Bundling data (attributes) and methods that operate on that
data within a single unit (object). It hides the implementation details of an
object from the outside world. This protects data from accidental modification
and improves code organization
7
Object Oriented Programming
Inheritance: Creating new classes (subclasses) based on existing classes
(superclasses). Subclasses inherit properties and methods from their parent
class, allowing for code reuse and creating hierarchical relationships.
Polymorphism: The ability of objects of different types to be treated as if
they were of the same type. It can be achieved through method
overloading (different methods with the same name but different
parameters) and method overriding (redefining a method in a subclass).
Abstraction: Focusing on essential features of an object while hiding
implementation details. This simplifies the interface and makes code easier
to understand and use
8
Example
class Person:
def __init__(self, name, age): # Constructor
self.name = name
self.age = age
def info(self):
return f"Name is {self.name} and Age is {self.age} years."
# Creating an instance (object) of the Person class
person1 = Person("Zia", 13)
print(person1.info()) # Output: Name is Zia and Age is 13 years
9
Class Variables vs. Instance Variables
Class Variables
Defined at the class level, outside of any methods.
Shared by all instances of the class.
Accessed using the class name or an instance.
Useful for storing data that is common to all objects of the class.
Instance Variables
Defined within a method, typically in the constructor (__init__).
Specific to each instance of the class.
Accessed using the self keyword within the instance methods.
Useful for storing data that is unique to each object.
10
Example
class Car:
# Class variable
wheels = 4
def __init__(self, color, model):
# Instance variables
self.color = color
self.model = model
car1= Car("White", "Alto")
car2= Car("Red", "Civic")
print(Car.wheels)
print(car1.wheels, car2.wheels)
print(car1.color,car1.model) 11
Class Functions (Methods):
Defined at the class level, outside of the constructor (__init__).
Operate on the class itself, not on specific object instances.
Accessed using the class name (similar to regular functions).
Can be used for utility functions or to modify the class itself.
Instance Functions (Methods):
Defined within the class.
Operate on specific instances (objects) of the class.
Accessed using the self keyword within the instance methods.
Used to define the behavior of objects and manipulate their attributes.
12
Example
class Dog:
species = "German Shepherd" # Class variable
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self): # Instance method
return f"{self.name} is barking."
@classmethod # a decorator is a design pattern that allows you to modify the behavior of a function or
method.
def species_info(cls): # Class method
return f"The species of dogs is {cls.species}."
13
Exmp…
my_dog = Dog(“Jack", 3)
# Calling instance method
print(my_dog.bark()) # Output: Jack is barking.
# Calling class method
print(Dog.species_info()) #The species of dogs is German Shepherd
14
Constructor & Destructor
A constructor in Python is a special method called __init__ that is
automatically invoked when an object of a class is created. Its
primary purpose is to initialize the object's attributes with default or
provided values.
A destructor in Python is a special method called __del__ that is
invoked when an object is about to be destroyed or garbage
collected. In Python's garbage collector handles memory
management automatically, so destructors are less commonly used.
15
Example
class Person:
def __init__(self, name): # constructor
self.name = name
def __del__(self): # destructor
print(f"{self.name} is being destroyed")
# Creating an object
person1 = Person("Alice")
# Destructor will be called automatically when person1 goes out of
scope
16
Inheritance
Inheritance is a fundamental concept in object-oriented
programming (OOP) that allows you to create new classes (derived
classes or subclasses) based on existing classes (base classes or
superclasses). This promotes code reusability and helps organize
complex relationships between objects.
17
Inheritance
•Base class (superclass): The original class from which other classes inherit.
•Derived class (subclass): A new class that inherits properties and methods
from a base class.
How it works:
•A derived class automatically inherits all attributes and methods of the
base class.
•You can override or extend inherited methods in the derived class to
provide specific implementations.
•You can add new attributes and methods to the derived class.
18
Example
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
def eat(self):
return f"{self.name} is eating."
21
Multiple Inheritance
class Mammal:
def has_fur(self):
return True
class Pet:
def is_pet(self):
return True
class Dog(Animal, Mammal, Pet):
def speak(self):
return f"{self.name} says Woof!"
# The Dog class now inherits from Animal, Mammal, and Pet.
22
Multiple Inheritance
# Creating an instance of the Dog class
my_dog = Dog("Buddy")
# Calling methods from all parent classes
print(my_dog.eat()) # Output: Buddy is eating.
print(my_dog.speak()) # Output: Buddy says Woof!
print(my_dog.has_fur()) # Output: True
print(my_dog.is_pet()) # Output: True
23
Q&A
24