SlideShare a Scribd company logo
OOPS and Exception Handling
Dr. A. B. Shinde
Assistant Professor,
Electronics and Computer Science,
P V P Institute of Technology, Sangli
Dr. A. B. Shinde
Contents
• Classes and Objects,
• Self-variable,
• Methods,
• Constructor Method,
• Encapsulation,
• Inheritance,
• Polymorphism,
• Abstraction, Data Hiding,
• Method Overloading and Overriding.
• Exception Handling:
• Errors & Exceptions,
• Difference between Error and Exception,
• Exception Handling using try-except-finally blocks,
• Raising Exception,
• Exception Types: Built-in & User-defined Exceptions.
2
OOPs Concepts
Dr. A. B. Shinde
Dr. A. B. Shinde
OOPs Concepts
• Object-oriented programming – It uses objects in programming.
• The main aim of OOP is to bind together the data and the functions that
operate on them so that no other part of the code can access this data
except that function.
• There are some basic concepts that act as the building blocks of OOPs
• Class
• Object
• Encapsulation
• Abstraction
• Polymorphism
• Inheritance
• Dynamic Binding
• Message Passing
4
Dr. A. B. Shinde
OOPs Concepts
• Class:
• It is a user-defined data type, which holds its own data members and
member functions, which can be accessed and used by creating an
instance of that class.
• For Example: Consider the Class of Cars. There may be many cars
with different names and brands but all of them will share some
common properties like all of them will have 4 wheels, Speed Limit,
Mileage range, Brakes, Accelerator etc. So here, the Car is the class,
and wheels, speed limits, and mileage are their properties.
5
Dr. A. B. Shinde
OOPs Concepts
• Object:
• An Object is an instance of a Class.
• When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated.
• Objects take up space in memory and have an associated address.
• When a program is executed the objects interact by sending messages
to one another.
• Each object contains data and code to manipulate the data.
• Objects can interact without having to know details of each other’s data
or code, it is sufficient to know the type of message accepted and the
type of response returned by the objects.
6
Dr. A. B. Shinde
OOPs Concepts
• Encapsulation:
• Encapsulation is defined as wrapping up data and information under a
single unit.
• In OOPs, Encapsulation is defined as binding together the data and the
functions that manipulate them.
• Example: In a company, there are different sections like the accounts
section, finance section, sales section, etc.
• Consider a situation when official from the finance section needs all the
data about sales in a particular month. In this case, he is not allowed to
directly access the data of the sales section. He will first have to contact the
officer in the sales section and then request him to give the particular data.
• Here the data of the sales section and the employees that can manipulate
them are wrapped under a single name “sales section”.
7
Dr. A. B. Shinde
OOPs Concepts
• Abstraction:
• Abstraction means displaying only essential information and hiding the
details.
• Data abstraction refers to providing only essential information about the
data to the outside world, hiding the background details or
implementation.
• Example: A man driving a car. The man only knows that pressing the
accelerator will increase the speed of the car or applying brakes will
stop the car but he does not know how on pressing the accelerator the
speed is actually increasing, he does not know about the inner
mechanism of the car or the implementation of an accelerator, brakes,
etc. in the car.
8
Dr. A. B. Shinde
OOPs Concepts
• Polymorphism:
• The word polymorphism means having many forms.
• Polymorphism is the ability of a message to be displayed in more than
one form.
• Example: A man at the same time is a father, a husband, and an
employee. So the same person possesses different behavior in
different situations. This is called polymorphism. An operation may
exhibit different behaviors in different instances. The behavior depends
upon the types of data used in the operation.
9
Dr. A. B. Shinde
OOPs Concepts
• Inheritance:
• The capability of a class to derive properties and characteristics from
another class is called Inheritance.
• Sub Class: The class that inherits properties from another class is
called Sub class or Derived Class.
• Super Class: The class whose properties are inherited by a sub-class
is called Base Class or Superclass.
10
Dr. A. B. Shinde
OOPs Concepts
• Dynamic Binding:
• In dynamic binding, the code to be executed in response to the function
call is decided at runtime.
• Because dynamic binding is flexible, it avoids the drawbacks of static
binding, which connected the function call and definition at build time.
11
Dr. A. B. Shinde
OOPs Concepts
• Message Passing:
• Objects communicate with one another by sending and receiving
information.
• A message for an object is a request for the execution of a procedure
and therefore will invoke a function in the receiving object that
generates the desired results.
• Message passing involves specifying the name of the object, the name
of the function, and the information to be sent.
12
Python OOPs Concepts
Dr. A. B. Shinde
Dr. A. B. Shinde
Python OOPs Concepts
• Object Oriented Programming is a fundamental concept in Python,
empowering developers to build modular, maintainable, and scalable
applications.
• By understanding the core OOP principles (classes, objects,
inheritance, encapsulation, polymorphism, and abstraction),
programmers can utilize the full potential of Python OOP capabilities for
solving complex problems.
• OOPs is a way of organizing code that uses objects and classes to
represent real-world entities and their behavior.
14
Python Classes and Objects
Dr. A. B. Shinde
Dr. A. B. Shinde
Python Classes and Objects
• A class in Python is a user-defined template for creating objects.
• It bundles data and functions together, making it easier to manage and
use them.
• When we create a new class, we define a new type of object.
• Classes are created using class keyword.
• Attributes are variables defined inside the class and represent the
properties of the class.
• Attributes can be accessed using the dot (.) operator
e.g., MyClass.my_attribute
16
Dr. A. B. Shinde
Python Classes and Objects
• Create a Class
• Classes are created using class keyword.
17
• Create Object
• An Object is an instance of a Class. It represents a specific implementation of
the class and holds its own data.
sound attribute is a class
attribute. It is shared
across all instances of Dog
class, so can be directly
accessed through
instance dog1
Dr. A. B. Shinde
Python Classes and Objects
• Using __init__() Function
• In Python, class has __init__() function. It automatically initializes object
attributes when an object is created.
18
class Dog:
species = "Canine" # Class attribute
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute
Explanation:
 class Dog : Defines a class named Dog.
 Species : A class attribute shared by all instances of the class.
 __init__ method: Initializes the name and age attributes when a new object is
created.
Dr. A. B. Shinde
Python Classes and Objects
• Initiate Object with __init__
19
• dog1 = Dog(“Buddy”, 3): Creates an object of the Dog class with name as
“Buddy” and age as 3.
• dog1.name : Accesses the instance attribute name of the dog1 object.
• dog1.species : Accesses the class attribute species of the dog1 object.
Self Variable
Dr. A. B. Shinde
Dr. A. B. Shinde
Self Variable
• Self parameter is a reference to the current instance of the class. It
allows us to access the attributes and methods of the object.
21
• self.name: Refers to the name attribute of the object (dog1) calling the
method.
• dog1.bark(): Calls the bark method on dog1.
Dr. A. B. Shinde
Self Variable
• __str__ Method
• __str__ method in Python allows us to define a custom string
representation of an object.
• When we print an object or convert it to a string using str(), Python
uses the default implementation, which returns a string like
<__main__.ClassName object at 0x00000123>.
22
Dr. A. B. Shinde
Self Variable
• __str__ Implementation: Defined as a method in the Dog class. Uses
the self parameter to access the instance’s attributes (name and age).
• Readable Output: When print(dog1) is called, Python automatically
uses the __str__ method to get a string representation of the object.
• Without __str__, calling print(dog1) would produce something like
<__main__.Dog object at 0x00000123>
23
Dr. A. B. Shinde
Self in Python
• Self represents the instance of the class.
• By using the “self” we can access the attributes and methods of the
class in Python.
• It binds the attributes with the given arguments.
• Use of self in Python?
• When working with classes in Python, the term “self” refers to the
instance of the class that is currently being used.
• Whenever you call a method of an object created from a class, the
object is automatically passed as the first argument using the “self”
parameter.
• This enables you to modify the object’s properties and execute tasks
unique to that particular instance
24
Dr. A. B. Shinde
Self in Python
• Self in Python:
25
Dr. A. B. Shinde
Self in Python
• Class self Constructor:
• In Python, a class constructor is a special method named __init__ that
gets called when you create an instance (object) of a class.
• This method is used to initialize the attributes of the object.
• The self parameter in the constructor refers to the instance being
created and allows you to access and set its attributes.
26
Dr. A. B. Shinde
Self in Python
• Class self Constructor:
27
Dr. A. B. Shinde
Self in Python
• Self: Pointer to Current Object
• The self is always pointing to the Current Object.
• When you create an instance of a class, you’re essentially creating an
object with its own set of attributes and methods
28
Dr. A. B. Shinde
Self in Python
• Creating Class with Attributes and Methods
29
Dr. A. B. Shinde
Self in Python
• Self: Convention, Not Keyword
• Self is a convention and not a Python keyword.
• Self is a parameter in instance method and the user can use another
parameter name in place of it.
• But it is advisable to use self because it increases the readability of
code.
30
Constructor in Python
Dr. A. B. Shinde
Dr. A. B. Shinde
Constructor in Python
• In Python, a constructor is a special method that is called
automatically when an object is created from a class.
• Its main role is to initialize the object by setting up its attributes or state.
• The method __new__ is the constructor that creates a new instance
of the class while __init__ is the initializer that sets up the instance’s
attributes after creation.
• These methods work together to manage object creation and
initialization.
32
Dr. A. B. Shinde
Constructor in Python
• __new__ Method
• This method is responsible for creating a new instance of a class.
• It allocates memory and returns the new object.
• It is called before __init__.
• Syntax
33
Dr. A. B. Shinde
Constructor in Python
• __init__ Method
• This method initializes the newly created instance and is commonly
used as a constructor in Python.
• It is called immediately after the object is created by __new__ method
and is responsible for initializing attributes of the instance.
• Syntax
34
Dr. A. B. Shinde
Constructor in Python
• Differences between __init__ and __new__
• __new__ method:
• Responsible for creating a new instance of the class.
• Rarely dominated but useful for customizing object creation and
especially in immutable objects.
• __init__ method:
• Called immediately after __new__.
• Used to initialize the created object.
35
Dr. A. B. Shinde
Constructor in Python
• Default Constructor:
• A default constructor does not take any parameters other than self.
• It initializes the object with default attribute values.
36
Dr. A. B. Shinde
Constructor in Python
• Parameterized Constructor:
• A parameterized constructor accepts arguments to initialize the
object’s attributes with specific values
37
Encapsulation in Python
Dr. A. B. Shinde
Dr. A. B. Shinde
Encapsulation
• In Python, encapsulation refers to the bundling of data (attributes) and
methods (functions) that operate on the data into a single unit, typically
a class.
• It also restricts direct access to some components, which helps protect
the integrity of the data and ensures proper usage.
39
Dr. A. B. Shinde
Encapsulation
• Encapsulation is the process of hiding the internal state of an object and
requiring all interactions to be performed through an object’s methods.
This approach:
• Provides better control over data.
• Prevents accidental modification of data.
• Promotes modular programming.
• Python achieves encapsulation through public, private and protected
attributes.
40
Dr. A. B. Shinde
Encapsulation
• How Encapsulation Works :
• Data Hiding: The variables (attributes) are kept private or protected,
meaning they are not accessible directly from outside the class.
Instead, they can only be accessed or modified through the methods.
• Access through Methods: Methods act as the interface through which
external code interacts with the data stored in the variables. For
instance, getters and setters are common methods used to retrieve and
update the value of a private variable.
• Control and Security: By encapsulating the variables and only
allowing their manipulation via methods, the class can enforce rules on
how the variables are accessed or modified, thus maintaining control
and security over the data.
41
Dr. A. B. Shinde
Encapsulation
• Example of Encapsulation
• Encapsulation in Python is like having a bank account system where
your account balance (data) is kept private. You can’t directly change
your balance by accessing the account database. Instead, the bank
provides you with methods (functions) like deposit and withdraw to
modify your balance safely.
• Private Data (Balance): Your balance is stored securely. Direct access
from outside is not allowed, ensuring the data is protected from
unauthorized changes.
• Public Methods (Deposit and Withdraw): These are the only ways to
modify your balance. They check if your requests (like withdrawing
money) follow the rules (e.g., you have enough balance) before
allowing changes.
42
Dr. A. B. Shinde
Encapsulation
• Public Members
• Public members are accessible from anywhere, both inside and outside
the class. These are the default members in Python.
43
• Public Attribute
(name): This attribute is
declared without any
underscore prefixes.
• It is accessible from
anywhere, both inside and
outside of the class.
• Public Method (display_name): This method is also accessible from any
part of the code. It directly accesses the public attribute and prints its value.
• Object (obj): An instance of Public is created, and the display_name method
is called, demonstrating how public attributes and methods can be accessed
directly.
Dr. A. B. Shinde
Encapsulation
• Protected members
• Protected members are identified with a single underscore (_).
• They are meant to be accessed only within the class or its subclasses.
44
• Protected Attribute (_age): This
attribute is prefixed with a single
underscore, which by convention,
suggests that it should be treated
as a protected member. It’s not
enforced by Python but indicates
that it should not be accessed
outside of this class and its
subclasses.
• Subclass: Here, a subclass inherits from Protected. Within this subclass, we
can still access the protected attribute _age.
• Method (display_age): This method within the subclass accesses the
protected attribute and prints its value. This shows that protected members
can be accessed within the class and its subclasses.
Dr. A. B. Shinde
Encapsulation
• Private members
• Private members are identified with a double underscore (__) and
cannot be accessed directly from outside the class.
• Python uses name mangling to make private members inaccessible by
renaming them internally.
45
Dr. A. B. Shinde
Encapsulation 46
• Private Attribute (__salary): This attribute is prefixed with two underscores,
which makes it a private member. Python enforces privacy by name
mangling, which means it renames the attribute in a way that makes it hard
to access from outside the class.
• Method (salary): This public method provides the only way to access the
private attribute from outside the class. It safely returns the value of __salary.
• Direct Access Attempt: Trying to access the private attribute directly
(obj.__salary) will result in an AttributeError, showing that direct access is
blocked. This is Python’s way of enforcing encapsulation at a language level.
Inheritance in Python
Dr. A. B. Shinde
Dr. A. B. Shinde
Inheritance
• Inheritance is a fundamental concept in OOP, that allows a class (child
or derived class) to inherit attributes and methods from another class
(parent or base class).
• This promotes code reuse, modularity, and a hierarchical class
structure.
48
Dr. A. B. Shinde
Inheritance
• Syntax for Inheritance
49
• Parent Class:
– This is the base class from which other classes inherit.
– It contains attributes and methods that the child class can reuse.
• Child Class:
– This is the derived class that inherits from the parent class.
– The syntax for inheritance is class ChildClass(ParentClass).
– The child class automatically gets all attributes and methods of the
parent class unless overridden.
class Parent_Class:
# Parent class code here
pass
class Child_Class(Parent_Class):
# Child class code here
pass
Dr. A. B. Shinde
Inheritance
• Creating a Parent Class
• In object-oriented programming, a parent class (also known as a base
class) defines common attributes and methods that can be inherited by
other classes. These attributes and methods serve as the foundation for the
child classes. By using inheritance, child classes can access and extend
the functionality provided by the parent class.
50
Dr. A. B. Shinde
Inheritance
• Creating a Child Class
• A child class (also known as a subclass) is a class that inherits
properties and methods from its parent class. The child class can also
introduce additional attributes and methods, or even override the ones
inherited from the parent.
• In this case, Emp is the child class that inherits from the Person class:
51
Dr. A. B. Shinde
Inheritance
• __init__() Function
• __init__() function is a constructor method in Python. It initializes the
object’s state when the object is created. If the child class does not define
its own __init__() method, it will automatically inherit the one from the
parent class.
• In the example above, the __init__() method in the Employee class ensures
that both inherited and new attributes are properly initialized.
52
Dr. A. B. Shinde
Inheritance
• super() Function
• super() function is used to call the parent class’s methods. In particular,
it is commonly used in the child class’s __init__() method to initialize
inherited attributes. This way, the child class can leverage the
functionality of the parent class.
53
Dr. A. B. Shinde
Inheritance
• Types of Python Inheritance
• Single Inheritance: A child class inherits from one parent class.
• Multiple Inheritance: A child class inherits from more than one parent
class.
• Multilevel Inheritance: A class is derived from a class which is also
derived from another class.
• Hierarchical Inheritance: Multiple classes inherit from a single parent
class.
• Hybrid Inheritance: A combination of more than one type of
inheritance.
54
Dr. A. B. Shinde
Inheritance
Single Inheritance
55
Base Class
Child Class
Multiple Inheritance
Base Class 1 Base Class 2
Derived Class
Multi level Inheritance
Polymorphism in Python
Dr. A. B. Shinde
Dr. A. B. Shinde
Polymorphism
• Polymorphism is a foundational concept in programming that allows
entities like functions, methods or operators to behave differently based
on the type of data they are handling.
• Derived from Greek, the term means “many forms”.
• Python’s dynamic typing and duck typing make it inherently
polymorphic.
• Functions, operators and even built-in objects like loops exhibit
polymorphic behavior.
57
Duck Typing is a type system used in
dynamic languages like Python, Perl,
Ruby, PHP, Javascript, etc. where the type
or the class of an object is less important
than the method it defines.
Dr. A. B. Shinde
Polymorphism
• Polymorphism in Built-in Functions:
• Python’s built-in functions exhibit polymorphism, adapting to various
data types.
58
Dr. A. B. Shinde
Polymorphism
• Polymorphism in Functions:
• Duck typing enables functions to work with any object regardless of its
type.
59
Dr. A. B. Shinde
Polymorphism
• Polymorphism in Operators:
• Operator Overloading:
• In Python, operators like + behave polymorphically, performing
addition, concatenation or merging based on the data type.
60
Dr. A. B. Shinde
Polymorphism
• Polymorphism in OOPs:
• In OOP, polymorphism allows methods in different classes to share the
same name but perform distinct tasks.
• This is achieved through inheritance and interface design.
• Polymorphism complements other OOP principles
like inheritance (sharing behavior) and encapsulation (hiding
complexity) to create robust and modular applications.
61
Dr. A. B. Shinde
Polymorphism
• Polymorphism in OOPs:
62
• Parent Class Shape: Contains a generic
area method returning “Undefined”,
acting as a placeholder for derived
classes to override.
• Child Class Rectangle: Initializes length
and width via the __init__ constructor.
Overrides the area method to return the
rectangle’s area as length * width.
• Child Class Circle: Initializes radius via
the __init__ constructor. Overrides the
area method to return the circle’s area as
3.14 * radius^2.
• Polymorphic Behavior: A list of shape
objects (Rectangle and Circle) is created.
A for loop iterates through the list, calling
the area method on each object. The
method executed is determined by the
object’s type, showcasing polymorphism.
Dr. A. B. Shinde
Polymorphism
• Types of Polymorphism:
• Compile-time Polymorphism
• Found in statically typed languages like Java or C++, where the
behavior of a function or operator is resolved during the program’s
compilation phase.
• Examples include method overloading and operator overloading, where
multiple functions or operators can share the same name but perform
different tasks based on the context.
• In Python, (dynamically typed), compile-time polymorphism is not
supported. Instead, Python uses techniques like dynamic typing and
duck typing to achieve similar flexibility.
63
Dr. A. B. Shinde
Polymorphism
• Types of Polymorphism:
• Runtime Polymorphism
• Occurs when the behavior of a
method is determined at runtime
based on the type of the object.
• In Python, this is achieved
through method overriding: a child
class can redefine a method from
its parent class to provide its own
specific implementation.
• Python’s dynamic nature allows it
to excel at runtime polymorphism,
enabling flexible and adaptable
code.
64
Dr. A. B. Shinde
Polymorphism
• Types of Polymorphism:
• Inheritance Class Polymorphism
• Inheritance-based polymorphism occurs when a subclass overrides a
method from its parent class, providing a specific implementation. This
process of re-implementing a method in the child class is known
as Method Overriding.
65
• Class Animal: Acts as the base (parent) class. Contains
a method sound that provides a default behavior,
returning “Some generic animal sound”. This serves as
a generic representation of the sound method for all
animals.
• Class Dog: Inherits from the Animal class (denoted by
class Dog(Animal)). Overrides the sound method to
return “Woof Woof!”, a behavior specific to dogs. This
demonstrates method overriding, where the subclass
modifies the implementation of the parent class’s
method.
• Class Cat: Inherits from the Animal class (denoted by
class Cat(Animal)). Overrides the sound method to
return “Meow”, a behavior specific to cats. Like Dog,
this also demonstrates method overriding.
Data Abstraction in Python
Dr. A. B. Shinde
Dr. A. B. Shinde
Data Abstraction in Python
• Data abstraction is one of the most essential concepts of Python OOPs
which is used to hide irrelevant details from the user and show the
details that are relevant to the users.
• Example 1: Our class students only know that a I am preparing the
*.ppt of python lectures and when it gets shared on classroom,
students can read the contents but the students are not aware of the
background process of *.ppt preparation.
• Example 2: A simple example of this can be a car. A car has an
accelerator, clutch, and break and we all know that pressing an
accelerator will increase the speed of the car and applying the brake
can stop the car but we don't know the internal mechanism of the car
and how these functionalities can work this detail hiding is known as
data abstraction.
67
Dr. A. B. Shinde
Data Abstraction in Python
• Importance of Data Abstraction
• It enables programmers to hide complex implementation details while
just showing users the most crucial data and functions.
• This abstraction makes it easier to design modular and well-organized
code, makes it simpler to understand and maintain, promotes code
reuse, and improves developer collaboration.
• Data Abstraction in Python
• Data abstraction in Python is a programming concept that hides
complex implementation details while exposing only essential
information and functionalities to users.
• In Python, we can achieve data abstraction by using abstract classes
and abstract classes can be created using abc (abstract base class)
module @abstractmethod of abc module.
68
Dr. A. B. Shinde
Data Abstraction in Python
• Abstraction classes in Python
• Abstract class is a class in which one or more abstract methods are
defined. When a method is declared inside the class without its
implementation is known as abstract method.
• Abstract Method: This feature is not a default feature.
• To create abstract method and abstract classes we have to import the
"ABC" and "abstractmethod" classes from abc (Abstract Base Class)
library.
• Abstract method of base class force its child class to write the
implementation of the all abstract methods defined in base class.
69
Dr. A. B. Shinde
Data Abstraction in Python
• Abstraction classes in Python
• Abstract Method: Abstract methods are methods that are defined in an
abstract class but do not have an implementation. They serve as a
blueprint for the subclasses, ensuring that they provide their own
implementation.
70
Dr. A. B. Shinde
Data Abstraction in Python
• Abstraction classes in Python
• Concrete Method: Concrete methods are the methods defined in an
abstract base class with their complete implementation.
• Concrete methods are required to avoid replication of code in
subclasses.
• For example: In abstract base class there may be a method that
implementation is to be same in all its subclasses, so we write the
implementation of that method in abstract base class after which we do
not need to write implementation of the concrete method again and
again in every subclass.
71
Dr. A. B. Shinde
Data Abstraction in Python
• Abstraction classes in Python
• Concrete methods are methods that have full implementations in an
abstract class.
• These methods can be inherited by subclasses and used directly
without needing to be redefined.
72
Exception Handling in Python
Dr. A. B. Shinde
Dr. A. B. Shinde
Python Exception Handling
• Python Exception Handling handles errors that occur during the
execution of a program.
• Exception handling allows to respond to the error, instead of crashing
the running program.
• It enables you to catch and manage errors, making your code more
robust and user-friendly.
• Example:
74
Dr. A. B. Shinde
Python Exception Handling
• Difference Between Exception and Error
• Error: Errors are serious issues that a program should not try to
handle.
• They are usually problems in the code's logic or configuration and need
to be fixed by the programmer.
• Examples include syntax errors and memory errors.
• Exception: Exceptions are less severe than errors and can be handled
by the program.
• They occur due to situations like invalid input, missing files or network
issues.
75
Dr. A. B. Shinde
Python Exception Handling
• try, except, else and finally Blocks:
• try Block: test a block of code for errors. Python will "try" to execute
the code in this block. If an exception occurs, execution will immediately
jump to the except block.
• except Block: It enables us to handle the error or exception. If the
code inside the try block throws an error, Python jumps to the except
block and executes it.
• else Block: It is optional and if included, must follow all except blocks.
The else block runs only if no exceptions are raised in the try block.
• finally Block: It always runs, regardless of whether an exception
occurred or not. It is typically used for cleanup operations (closing files,
releasing resources).
76
Dr. A. B. Shinde
Python Exception Handling
• try, except, else and finally Blocks:
77
Dr. A. B. Shinde
Python Exception Handling
• Common Exceptions in Python:
78
Exception Name Description
BaseException The base class for all built-in exceptions.
Exception The base class for all non-exit exceptions.
ArithmeticError
Base class for all errors related to
arithmetic operations.
ZeroDivisionError
Raised when a division or modulo
operation is performed with zero as the
divisor.
OverflowError
Raised when a numerical operation
exceeds the maximum limit of a data type.
FloatingPointError
Raised when a floating-point operation
fails.
AssertionError Raised when an assert statement fails.
AttributeError
Raised when an attribute reference or
assignment fails.
IndexError
Raised when a sequence subscript is out
of range.
KeyError Raised when a dictionary key is not found.
Exception Name Description
MemoryError
Raised when an operation runs
out of memory.
NameError
Raised when a local or global
name is not found.
OSError
Raised when a system-related
operation (like file I/O) fails.
TypeError
Raised when an operation or
function is applied to an object
of inappropriate type.
ValueError
Raised when a function
receives an argument of the
right type but inappropriate
value.
ImportError
Raised when an import
statement has issues.
ModuleNotFoundError
Raised when a module cannot
be found.
Dr. A. B. Shinde
Python Exception Handling
• Raise an Exception:
• We raise an exception in Python using the raise keyword followed by
an instance of the exception class that we want to trigger.
• We can choose from built-in exceptions or define our own custom
exceptions by inheriting from Python's built-in Exception class.
79
Dr. A. B. Shinde
Python Exception Handling
• Advantages of Exception Handling:
• Improved program reliability: By handling exceptions properly, you
can prevent your program from crashing or producing incorrect results
due to unexpected errors or input.
• Simplified error handling: Exception handling allows you to separate
error handling code from the main program logic, making it easier to
read and maintain your code.
• Cleaner code: With exception handling, you can avoid using complex
conditional statements to check for errors, leading to cleaner and more
readable code.
• Easier debugging: When an exception is raised, the Python interpreter
prints a traceback that shows the exact location where the exception
occurred, making it easier to debug your code.
80
Dr. A. B. Shinde
Python Exception Handling
• Disadvantages of Exception Handling:
• Performance overhead: Exception handling can be slower than using
conditional statements to check for errors, as the interpreter has to
perform additional work to catch and handle the exception.
• Increased code complexity: Exception handling can make your code
more complex, especially if you have to handle multiple types of
exceptions or implement complex error handling logic.
• Possible security risks: Improperly handled exceptions can potentially
reveal sensitive information or create security vulnerabilities in your
code, so it's important to handle exceptions carefully and avoid
exposing too much information about your program.
81
82
This presentation is published only for educational purpose
Thank You…
abshinde.eln@gmail.com

More Related Content

Similar to OOPS Concepts in Python and Exception Handling (20)

DOC
C# by Zaheer Abbas Aghani
Information Technology Center
 
PPT
07slide.ppt
NuurAxmed2
 
PPTX
Object oriented programming
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Lesson 1 - Introduction to Object Oriented Concepts.pptx
dikshaprabhugvm
 
PPTX
slides11-objects_and_classes in python.pptx
debasisdas225831
 
PPTX
Lecture 5.pptx
AshutoshTrivedi30
 
PPTX
Class and Objects in python programming.pptx
Rajtherock
 
PDF
80410172053.pdf
WrushabhShirsat3
 
PPTX
Fundamentals of OOP (Object Oriented Programming)
MD Sulaiman
 
PPTX
java - oop's in depth journey
Sudharsan Selvaraj
 
PPTX
introduction of Object oriented programming
RiturajJain8
 
PPTX
Object Oriented Programming Tutorial.pptx
ethiouniverse
 
PDF
L1-Introduction to OOPs concepts.pdf
BhanuJatinSingh
 
PPTX
Python aplicado a Inteligencia artificial y machine learning. Dia 91.
chekov2500
 
PPTX
Object oriented programming 6 oop with c++
Vaibhav Khanna
 
PPTX
oop.pptx
KabitaParajuli3
 
PPTX
Principles of OOPs.pptx
LakshyaChauhan21
 
PPTX
[OOP - Lec 04,05] Basic Building Blocks of OOP
Muhammad Hammad Waseem
 
PPTX
basic concepts of object oriented in python
deepalishinkar1
 
PPTX
1_Object Oriented Programming.pptx
umarAnjum6
 
C# by Zaheer Abbas Aghani
Information Technology Center
 
07slide.ppt
NuurAxmed2
 
Lesson 1 - Introduction to Object Oriented Concepts.pptx
dikshaprabhugvm
 
slides11-objects_and_classes in python.pptx
debasisdas225831
 
Lecture 5.pptx
AshutoshTrivedi30
 
Class and Objects in python programming.pptx
Rajtherock
 
80410172053.pdf
WrushabhShirsat3
 
Fundamentals of OOP (Object Oriented Programming)
MD Sulaiman
 
java - oop's in depth journey
Sudharsan Selvaraj
 
introduction of Object oriented programming
RiturajJain8
 
Object Oriented Programming Tutorial.pptx
ethiouniverse
 
L1-Introduction to OOPs concepts.pdf
BhanuJatinSingh
 
Python aplicado a Inteligencia artificial y machine learning. Dia 91.
chekov2500
 
Object oriented programming 6 oop with c++
Vaibhav Khanna
 
oop.pptx
KabitaParajuli3
 
Principles of OOPs.pptx
LakshyaChauhan21
 
[OOP - Lec 04,05] Basic Building Blocks of OOP
Muhammad Hammad Waseem
 
basic concepts of object oriented in python
deepalishinkar1
 
1_Object Oriented Programming.pptx
umarAnjum6
 

More from Dr. A. B. Shinde (20)

PDF
Python Programming Laboratory Manual for Students
Dr. A. B. Shinde
 
PPSX
Python Functions, Modules and Packages
Dr. A. B. Shinde
 
PPSX
Python Data Types, Operators and Control Flow
Dr. A. B. Shinde
 
PPSX
Introduction to Python programming language
Dr. A. B. Shinde
 
PPSX
Communication System Basics
Dr. A. B. Shinde
 
PPSX
MOSFETs: Single Stage IC Amplifier
Dr. A. B. Shinde
 
PPSX
MOSFETs
Dr. A. B. Shinde
 
PPSX
Color Image Processing: Basics
Dr. A. B. Shinde
 
PPSX
Edge Detection and Segmentation
Dr. A. B. Shinde
 
PPSX
Image Processing: Spatial filters
Dr. A. B. Shinde
 
PPSX
Image Enhancement in Spatial Domain
Dr. A. B. Shinde
 
DOCX
Resume Format
Dr. A. B. Shinde
 
PDF
Digital Image Fundamentals
Dr. A. B. Shinde
 
PPSX
Resume Writing
Dr. A. B. Shinde
 
PPSX
Image Processing Basics
Dr. A. B. Shinde
 
PPSX
Blooms Taxonomy in Engineering Education
Dr. A. B. Shinde
 
PPSX
ISE 7.1i Software
Dr. A. B. Shinde
 
PDF
VHDL Coding Syntax
Dr. A. B. Shinde
 
PDF
VHDL Programs
Dr. A. B. Shinde
 
PPSX
VLSI Testing Techniques
Dr. A. B. Shinde
 
Python Programming Laboratory Manual for Students
Dr. A. B. Shinde
 
Python Functions, Modules and Packages
Dr. A. B. Shinde
 
Python Data Types, Operators and Control Flow
Dr. A. B. Shinde
 
Introduction to Python programming language
Dr. A. B. Shinde
 
Communication System Basics
Dr. A. B. Shinde
 
MOSFETs: Single Stage IC Amplifier
Dr. A. B. Shinde
 
Color Image Processing: Basics
Dr. A. B. Shinde
 
Edge Detection and Segmentation
Dr. A. B. Shinde
 
Image Processing: Spatial filters
Dr. A. B. Shinde
 
Image Enhancement in Spatial Domain
Dr. A. B. Shinde
 
Resume Format
Dr. A. B. Shinde
 
Digital Image Fundamentals
Dr. A. B. Shinde
 
Resume Writing
Dr. A. B. Shinde
 
Image Processing Basics
Dr. A. B. Shinde
 
Blooms Taxonomy in Engineering Education
Dr. A. B. Shinde
 
ISE 7.1i Software
Dr. A. B. Shinde
 
VHDL Coding Syntax
Dr. A. B. Shinde
 
VHDL Programs
Dr. A. B. Shinde
 
VLSI Testing Techniques
Dr. A. B. Shinde
 
Ad

Recently uploaded (20)

PDF
Rapid Prototyping for XR: Lecture 3 - Video and Paper Prototyping
Mark Billinghurst
 
PDF
Rapid Prototyping for XR: Lecture 6 - AI for Prototyping and Research Directi...
Mark Billinghurst
 
PDF
13th International Conference of Security, Privacy and Trust Management (SPTM...
ijcisjournal
 
PDF
lesson4-occupationalsafetyandhealthohsstandards-240812020130-1a7246d0.pdf
arvingallosa3
 
PPTX
Tesla-Stock-Analysis-and-Forecast.pptx (1).pptx
moonsony54
 
PPTX
Work at Height training for workers .pptx
cecos12
 
PDF
May 2025: Top 10 Read Articles in Data Mining & Knowledge Management Process
IJDKP
 
PDF
Rapid Prototyping for XR: Lecture 5 - Cross Platform Development
Mark Billinghurst
 
PDF
June 2025 Top 10 Sites -Electrical and Electronics Engineering: An Internatio...
elelijjournal653
 
PPTX
Mobile database systems 20254545645.pptx
herosh1968
 
PDF
Plant Control_EST_85520-01_en_AllChanges_20220127.pdf
DarshanaChathuranga4
 
PPT
دراسة حاله لقرية تقع في جنوب غرب السودان
محمد قصص فتوتة
 
PPTX
CST413 KTU S7 CSE Machine Learning Clustering K Means Hierarchical Agglomerat...
resming1
 
PDF
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Mark Billinghurst
 
PDF
FSE-Journal-First-Automated code editing with search-generate-modify.pdf
cl144
 
PDF
Decision support system in machine learning models for a face recognition-bas...
TELKOMNIKA JOURNAL
 
PPTX
MATERIAL SCIENCE LECTURE NOTES FOR DIPLOMA STUDENTS
SAMEER VISHWAKARMA
 
PDF
Generative AI & Scientific Research : Catalyst for Innovation, Ethics & Impact
AlqualsaDIResearchGr
 
PPTX
Bitumen Emulsion by Dr Sangita Ex CRRI Delhi
grilcodes
 
PPT
SF 9_Unit 1.ppt software engineering ppt
AmarrKannthh
 
Rapid Prototyping for XR: Lecture 3 - Video and Paper Prototyping
Mark Billinghurst
 
Rapid Prototyping for XR: Lecture 6 - AI for Prototyping and Research Directi...
Mark Billinghurst
 
13th International Conference of Security, Privacy and Trust Management (SPTM...
ijcisjournal
 
lesson4-occupationalsafetyandhealthohsstandards-240812020130-1a7246d0.pdf
arvingallosa3
 
Tesla-Stock-Analysis-and-Forecast.pptx (1).pptx
moonsony54
 
Work at Height training for workers .pptx
cecos12
 
May 2025: Top 10 Read Articles in Data Mining & Knowledge Management Process
IJDKP
 
Rapid Prototyping for XR: Lecture 5 - Cross Platform Development
Mark Billinghurst
 
June 2025 Top 10 Sites -Electrical and Electronics Engineering: An Internatio...
elelijjournal653
 
Mobile database systems 20254545645.pptx
herosh1968
 
Plant Control_EST_85520-01_en_AllChanges_20220127.pdf
DarshanaChathuranga4
 
دراسة حاله لقرية تقع في جنوب غرب السودان
محمد قصص فتوتة
 
CST413 KTU S7 CSE Machine Learning Clustering K Means Hierarchical Agglomerat...
resming1
 
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Mark Billinghurst
 
FSE-Journal-First-Automated code editing with search-generate-modify.pdf
cl144
 
Decision support system in machine learning models for a face recognition-bas...
TELKOMNIKA JOURNAL
 
MATERIAL SCIENCE LECTURE NOTES FOR DIPLOMA STUDENTS
SAMEER VISHWAKARMA
 
Generative AI & Scientific Research : Catalyst for Innovation, Ethics & Impact
AlqualsaDIResearchGr
 
Bitumen Emulsion by Dr Sangita Ex CRRI Delhi
grilcodes
 
SF 9_Unit 1.ppt software engineering ppt
AmarrKannthh
 
Ad

OOPS Concepts in Python and Exception Handling

  • 1. OOPS and Exception Handling Dr. A. B. Shinde Assistant Professor, Electronics and Computer Science, P V P Institute of Technology, Sangli
  • 2. Dr. A. B. Shinde Contents • Classes and Objects, • Self-variable, • Methods, • Constructor Method, • Encapsulation, • Inheritance, • Polymorphism, • Abstraction, Data Hiding, • Method Overloading and Overriding. • Exception Handling: • Errors & Exceptions, • Difference between Error and Exception, • Exception Handling using try-except-finally blocks, • Raising Exception, • Exception Types: Built-in & User-defined Exceptions. 2
  • 4. Dr. A. B. Shinde OOPs Concepts • Object-oriented programming – It uses objects in programming. • The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function. • There are some basic concepts that act as the building blocks of OOPs • Class • Object • Encapsulation • Abstraction • Polymorphism • Inheritance • Dynamic Binding • Message Passing 4
  • 5. Dr. A. B. Shinde OOPs Concepts • Class: • It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. • For Example: Consider the Class of Cars. There may be many cars with different names and brands but all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range, Brakes, Accelerator etc. So here, the Car is the class, and wheels, speed limits, and mileage are their properties. 5
  • 6. Dr. A. B. Shinde OOPs Concepts • Object: • An Object is an instance of a Class. • When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated. • Objects take up space in memory and have an associated address. • When a program is executed the objects interact by sending messages to one another. • Each object contains data and code to manipulate the data. • Objects can interact without having to know details of each other’s data or code, it is sufficient to know the type of message accepted and the type of response returned by the objects. 6
  • 7. Dr. A. B. Shinde OOPs Concepts • Encapsulation: • Encapsulation is defined as wrapping up data and information under a single unit. • In OOPs, Encapsulation is defined as binding together the data and the functions that manipulate them. • Example: In a company, there are different sections like the accounts section, finance section, sales section, etc. • Consider a situation when official from the finance section needs all the data about sales in a particular month. In this case, he is not allowed to directly access the data of the sales section. He will first have to contact the officer in the sales section and then request him to give the particular data. • Here the data of the sales section and the employees that can manipulate them are wrapped under a single name “sales section”. 7
  • 8. Dr. A. B. Shinde OOPs Concepts • Abstraction: • Abstraction means displaying only essential information and hiding the details. • Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation. • Example: A man driving a car. The man only knows that pressing the accelerator will increase the speed of the car or applying brakes will stop the car but he does not know how on pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of an accelerator, brakes, etc. in the car. 8
  • 9. Dr. A. B. Shinde OOPs Concepts • Polymorphism: • The word polymorphism means having many forms. • Polymorphism is the ability of a message to be displayed in more than one form. • Example: A man at the same time is a father, a husband, and an employee. So the same person possesses different behavior in different situations. This is called polymorphism. An operation may exhibit different behaviors in different instances. The behavior depends upon the types of data used in the operation. 9
  • 10. Dr. A. B. Shinde OOPs Concepts • Inheritance: • The capability of a class to derive properties and characteristics from another class is called Inheritance. • Sub Class: The class that inherits properties from another class is called Sub class or Derived Class. • Super Class: The class whose properties are inherited by a sub-class is called Base Class or Superclass. 10
  • 11. Dr. A. B. Shinde OOPs Concepts • Dynamic Binding: • In dynamic binding, the code to be executed in response to the function call is decided at runtime. • Because dynamic binding is flexible, it avoids the drawbacks of static binding, which connected the function call and definition at build time. 11
  • 12. Dr. A. B. Shinde OOPs Concepts • Message Passing: • Objects communicate with one another by sending and receiving information. • A message for an object is a request for the execution of a procedure and therefore will invoke a function in the receiving object that generates the desired results. • Message passing involves specifying the name of the object, the name of the function, and the information to be sent. 12
  • 13. Python OOPs Concepts Dr. A. B. Shinde
  • 14. Dr. A. B. Shinde Python OOPs Concepts • Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. • By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can utilize the full potential of Python OOP capabilities for solving complex problems. • OOPs is a way of organizing code that uses objects and classes to represent real-world entities and their behavior. 14
  • 15. Python Classes and Objects Dr. A. B. Shinde
  • 16. Dr. A. B. Shinde Python Classes and Objects • A class in Python is a user-defined template for creating objects. • It bundles data and functions together, making it easier to manage and use them. • When we create a new class, we define a new type of object. • Classes are created using class keyword. • Attributes are variables defined inside the class and represent the properties of the class. • Attributes can be accessed using the dot (.) operator e.g., MyClass.my_attribute 16
  • 17. Dr. A. B. Shinde Python Classes and Objects • Create a Class • Classes are created using class keyword. 17 • Create Object • An Object is an instance of a Class. It represents a specific implementation of the class and holds its own data. sound attribute is a class attribute. It is shared across all instances of Dog class, so can be directly accessed through instance dog1
  • 18. Dr. A. B. Shinde Python Classes and Objects • Using __init__() Function • In Python, class has __init__() function. It automatically initializes object attributes when an object is created. 18 class Dog: species = "Canine" # Class attribute def __init__(self, name, age): self.name = name # Instance attribute self.age = age # Instance attribute Explanation:  class Dog : Defines a class named Dog.  Species : A class attribute shared by all instances of the class.  __init__ method: Initializes the name and age attributes when a new object is created.
  • 19. Dr. A. B. Shinde Python Classes and Objects • Initiate Object with __init__ 19 • dog1 = Dog(“Buddy”, 3): Creates an object of the Dog class with name as “Buddy” and age as 3. • dog1.name : Accesses the instance attribute name of the dog1 object. • dog1.species : Accesses the class attribute species of the dog1 object.
  • 20. Self Variable Dr. A. B. Shinde
  • 21. Dr. A. B. Shinde Self Variable • Self parameter is a reference to the current instance of the class. It allows us to access the attributes and methods of the object. 21 • self.name: Refers to the name attribute of the object (dog1) calling the method. • dog1.bark(): Calls the bark method on dog1.
  • 22. Dr. A. B. Shinde Self Variable • __str__ Method • __str__ method in Python allows us to define a custom string representation of an object. • When we print an object or convert it to a string using str(), Python uses the default implementation, which returns a string like <__main__.ClassName object at 0x00000123>. 22
  • 23. Dr. A. B. Shinde Self Variable • __str__ Implementation: Defined as a method in the Dog class. Uses the self parameter to access the instance’s attributes (name and age). • Readable Output: When print(dog1) is called, Python automatically uses the __str__ method to get a string representation of the object. • Without __str__, calling print(dog1) would produce something like <__main__.Dog object at 0x00000123> 23
  • 24. Dr. A. B. Shinde Self in Python • Self represents the instance of the class. • By using the “self” we can access the attributes and methods of the class in Python. • It binds the attributes with the given arguments. • Use of self in Python? • When working with classes in Python, the term “self” refers to the instance of the class that is currently being used. • Whenever you call a method of an object created from a class, the object is automatically passed as the first argument using the “self” parameter. • This enables you to modify the object’s properties and execute tasks unique to that particular instance 24
  • 25. Dr. A. B. Shinde Self in Python • Self in Python: 25
  • 26. Dr. A. B. Shinde Self in Python • Class self Constructor: • In Python, a class constructor is a special method named __init__ that gets called when you create an instance (object) of a class. • This method is used to initialize the attributes of the object. • The self parameter in the constructor refers to the instance being created and allows you to access and set its attributes. 26
  • 27. Dr. A. B. Shinde Self in Python • Class self Constructor: 27
  • 28. Dr. A. B. Shinde Self in Python • Self: Pointer to Current Object • The self is always pointing to the Current Object. • When you create an instance of a class, you’re essentially creating an object with its own set of attributes and methods 28
  • 29. Dr. A. B. Shinde Self in Python • Creating Class with Attributes and Methods 29
  • 30. Dr. A. B. Shinde Self in Python • Self: Convention, Not Keyword • Self is a convention and not a Python keyword. • Self is a parameter in instance method and the user can use another parameter name in place of it. • But it is advisable to use self because it increases the readability of code. 30
  • 32. Dr. A. B. Shinde Constructor in Python • In Python, a constructor is a special method that is called automatically when an object is created from a class. • Its main role is to initialize the object by setting up its attributes or state. • The method __new__ is the constructor that creates a new instance of the class while __init__ is the initializer that sets up the instance’s attributes after creation. • These methods work together to manage object creation and initialization. 32
  • 33. Dr. A. B. Shinde Constructor in Python • __new__ Method • This method is responsible for creating a new instance of a class. • It allocates memory and returns the new object. • It is called before __init__. • Syntax 33
  • 34. Dr. A. B. Shinde Constructor in Python • __init__ Method • This method initializes the newly created instance and is commonly used as a constructor in Python. • It is called immediately after the object is created by __new__ method and is responsible for initializing attributes of the instance. • Syntax 34
  • 35. Dr. A. B. Shinde Constructor in Python • Differences between __init__ and __new__ • __new__ method: • Responsible for creating a new instance of the class. • Rarely dominated but useful for customizing object creation and especially in immutable objects. • __init__ method: • Called immediately after __new__. • Used to initialize the created object. 35
  • 36. Dr. A. B. Shinde Constructor in Python • Default Constructor: • A default constructor does not take any parameters other than self. • It initializes the object with default attribute values. 36
  • 37. Dr. A. B. Shinde Constructor in Python • Parameterized Constructor: • A parameterized constructor accepts arguments to initialize the object’s attributes with specific values 37
  • 39. Dr. A. B. Shinde Encapsulation • In Python, encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. • It also restricts direct access to some components, which helps protect the integrity of the data and ensures proper usage. 39
  • 40. Dr. A. B. Shinde Encapsulation • Encapsulation is the process of hiding the internal state of an object and requiring all interactions to be performed through an object’s methods. This approach: • Provides better control over data. • Prevents accidental modification of data. • Promotes modular programming. • Python achieves encapsulation through public, private and protected attributes. 40
  • 41. Dr. A. B. Shinde Encapsulation • How Encapsulation Works : • Data Hiding: The variables (attributes) are kept private or protected, meaning they are not accessible directly from outside the class. Instead, they can only be accessed or modified through the methods. • Access through Methods: Methods act as the interface through which external code interacts with the data stored in the variables. For instance, getters and setters are common methods used to retrieve and update the value of a private variable. • Control and Security: By encapsulating the variables and only allowing their manipulation via methods, the class can enforce rules on how the variables are accessed or modified, thus maintaining control and security over the data. 41
  • 42. Dr. A. B. Shinde Encapsulation • Example of Encapsulation • Encapsulation in Python is like having a bank account system where your account balance (data) is kept private. You can’t directly change your balance by accessing the account database. Instead, the bank provides you with methods (functions) like deposit and withdraw to modify your balance safely. • Private Data (Balance): Your balance is stored securely. Direct access from outside is not allowed, ensuring the data is protected from unauthorized changes. • Public Methods (Deposit and Withdraw): These are the only ways to modify your balance. They check if your requests (like withdrawing money) follow the rules (e.g., you have enough balance) before allowing changes. 42
  • 43. Dr. A. B. Shinde Encapsulation • Public Members • Public members are accessible from anywhere, both inside and outside the class. These are the default members in Python. 43 • Public Attribute (name): This attribute is declared without any underscore prefixes. • It is accessible from anywhere, both inside and outside of the class. • Public Method (display_name): This method is also accessible from any part of the code. It directly accesses the public attribute and prints its value. • Object (obj): An instance of Public is created, and the display_name method is called, demonstrating how public attributes and methods can be accessed directly.
  • 44. Dr. A. B. Shinde Encapsulation • Protected members • Protected members are identified with a single underscore (_). • They are meant to be accessed only within the class or its subclasses. 44 • Protected Attribute (_age): This attribute is prefixed with a single underscore, which by convention, suggests that it should be treated as a protected member. It’s not enforced by Python but indicates that it should not be accessed outside of this class and its subclasses. • Subclass: Here, a subclass inherits from Protected. Within this subclass, we can still access the protected attribute _age. • Method (display_age): This method within the subclass accesses the protected attribute and prints its value. This shows that protected members can be accessed within the class and its subclasses.
  • 45. Dr. A. B. Shinde Encapsulation • Private members • Private members are identified with a double underscore (__) and cannot be accessed directly from outside the class. • Python uses name mangling to make private members inaccessible by renaming them internally. 45
  • 46. Dr. A. B. Shinde Encapsulation 46 • Private Attribute (__salary): This attribute is prefixed with two underscores, which makes it a private member. Python enforces privacy by name mangling, which means it renames the attribute in a way that makes it hard to access from outside the class. • Method (salary): This public method provides the only way to access the private attribute from outside the class. It safely returns the value of __salary. • Direct Access Attempt: Trying to access the private attribute directly (obj.__salary) will result in an AttributeError, showing that direct access is blocked. This is Python’s way of enforcing encapsulation at a language level.
  • 48. Dr. A. B. Shinde Inheritance • Inheritance is a fundamental concept in OOP, that allows a class (child or derived class) to inherit attributes and methods from another class (parent or base class). • This promotes code reuse, modularity, and a hierarchical class structure. 48
  • 49. Dr. A. B. Shinde Inheritance • Syntax for Inheritance 49 • Parent Class: – This is the base class from which other classes inherit. – It contains attributes and methods that the child class can reuse. • Child Class: – This is the derived class that inherits from the parent class. – The syntax for inheritance is class ChildClass(ParentClass). – The child class automatically gets all attributes and methods of the parent class unless overridden. class Parent_Class: # Parent class code here pass class Child_Class(Parent_Class): # Child class code here pass
  • 50. Dr. A. B. Shinde Inheritance • Creating a Parent Class • In object-oriented programming, a parent class (also known as a base class) defines common attributes and methods that can be inherited by other classes. These attributes and methods serve as the foundation for the child classes. By using inheritance, child classes can access and extend the functionality provided by the parent class. 50
  • 51. Dr. A. B. Shinde Inheritance • Creating a Child Class • A child class (also known as a subclass) is a class that inherits properties and methods from its parent class. The child class can also introduce additional attributes and methods, or even override the ones inherited from the parent. • In this case, Emp is the child class that inherits from the Person class: 51
  • 52. Dr. A. B. Shinde Inheritance • __init__() Function • __init__() function is a constructor method in Python. It initializes the object’s state when the object is created. If the child class does not define its own __init__() method, it will automatically inherit the one from the parent class. • In the example above, the __init__() method in the Employee class ensures that both inherited and new attributes are properly initialized. 52
  • 53. Dr. A. B. Shinde Inheritance • super() Function • super() function is used to call the parent class’s methods. In particular, it is commonly used in the child class’s __init__() method to initialize inherited attributes. This way, the child class can leverage the functionality of the parent class. 53
  • 54. Dr. A. B. Shinde Inheritance • Types of Python Inheritance • Single Inheritance: A child class inherits from one parent class. • Multiple Inheritance: A child class inherits from more than one parent class. • Multilevel Inheritance: A class is derived from a class which is also derived from another class. • Hierarchical Inheritance: Multiple classes inherit from a single parent class. • Hybrid Inheritance: A combination of more than one type of inheritance. 54
  • 55. Dr. A. B. Shinde Inheritance Single Inheritance 55 Base Class Child Class Multiple Inheritance Base Class 1 Base Class 2 Derived Class Multi level Inheritance
  • 57. Dr. A. B. Shinde Polymorphism • Polymorphism is a foundational concept in programming that allows entities like functions, methods or operators to behave differently based on the type of data they are handling. • Derived from Greek, the term means “many forms”. • Python’s dynamic typing and duck typing make it inherently polymorphic. • Functions, operators and even built-in objects like loops exhibit polymorphic behavior. 57 Duck Typing is a type system used in dynamic languages like Python, Perl, Ruby, PHP, Javascript, etc. where the type or the class of an object is less important than the method it defines.
  • 58. Dr. A. B. Shinde Polymorphism • Polymorphism in Built-in Functions: • Python’s built-in functions exhibit polymorphism, adapting to various data types. 58
  • 59. Dr. A. B. Shinde Polymorphism • Polymorphism in Functions: • Duck typing enables functions to work with any object regardless of its type. 59
  • 60. Dr. A. B. Shinde Polymorphism • Polymorphism in Operators: • Operator Overloading: • In Python, operators like + behave polymorphically, performing addition, concatenation or merging based on the data type. 60
  • 61. Dr. A. B. Shinde Polymorphism • Polymorphism in OOPs: • In OOP, polymorphism allows methods in different classes to share the same name but perform distinct tasks. • This is achieved through inheritance and interface design. • Polymorphism complements other OOP principles like inheritance (sharing behavior) and encapsulation (hiding complexity) to create robust and modular applications. 61
  • 62. Dr. A. B. Shinde Polymorphism • Polymorphism in OOPs: 62 • Parent Class Shape: Contains a generic area method returning “Undefined”, acting as a placeholder for derived classes to override. • Child Class Rectangle: Initializes length and width via the __init__ constructor. Overrides the area method to return the rectangle’s area as length * width. • Child Class Circle: Initializes radius via the __init__ constructor. Overrides the area method to return the circle’s area as 3.14 * radius^2. • Polymorphic Behavior: A list of shape objects (Rectangle and Circle) is created. A for loop iterates through the list, calling the area method on each object. The method executed is determined by the object’s type, showcasing polymorphism.
  • 63. Dr. A. B. Shinde Polymorphism • Types of Polymorphism: • Compile-time Polymorphism • Found in statically typed languages like Java or C++, where the behavior of a function or operator is resolved during the program’s compilation phase. • Examples include method overloading and operator overloading, where multiple functions or operators can share the same name but perform different tasks based on the context. • In Python, (dynamically typed), compile-time polymorphism is not supported. Instead, Python uses techniques like dynamic typing and duck typing to achieve similar flexibility. 63
  • 64. Dr. A. B. Shinde Polymorphism • Types of Polymorphism: • Runtime Polymorphism • Occurs when the behavior of a method is determined at runtime based on the type of the object. • In Python, this is achieved through method overriding: a child class can redefine a method from its parent class to provide its own specific implementation. • Python’s dynamic nature allows it to excel at runtime polymorphism, enabling flexible and adaptable code. 64
  • 65. Dr. A. B. Shinde Polymorphism • Types of Polymorphism: • Inheritance Class Polymorphism • Inheritance-based polymorphism occurs when a subclass overrides a method from its parent class, providing a specific implementation. This process of re-implementing a method in the child class is known as Method Overriding. 65 • Class Animal: Acts as the base (parent) class. Contains a method sound that provides a default behavior, returning “Some generic animal sound”. This serves as a generic representation of the sound method for all animals. • Class Dog: Inherits from the Animal class (denoted by class Dog(Animal)). Overrides the sound method to return “Woof Woof!”, a behavior specific to dogs. This demonstrates method overriding, where the subclass modifies the implementation of the parent class’s method. • Class Cat: Inherits from the Animal class (denoted by class Cat(Animal)). Overrides the sound method to return “Meow”, a behavior specific to cats. Like Dog, this also demonstrates method overriding.
  • 66. Data Abstraction in Python Dr. A. B. Shinde
  • 67. Dr. A. B. Shinde Data Abstraction in Python • Data abstraction is one of the most essential concepts of Python OOPs which is used to hide irrelevant details from the user and show the details that are relevant to the users. • Example 1: Our class students only know that a I am preparing the *.ppt of python lectures and when it gets shared on classroom, students can read the contents but the students are not aware of the background process of *.ppt preparation. • Example 2: A simple example of this can be a car. A car has an accelerator, clutch, and break and we all know that pressing an accelerator will increase the speed of the car and applying the brake can stop the car but we don't know the internal mechanism of the car and how these functionalities can work this detail hiding is known as data abstraction. 67
  • 68. Dr. A. B. Shinde Data Abstraction in Python • Importance of Data Abstraction • It enables programmers to hide complex implementation details while just showing users the most crucial data and functions. • This abstraction makes it easier to design modular and well-organized code, makes it simpler to understand and maintain, promotes code reuse, and improves developer collaboration. • Data Abstraction in Python • Data abstraction in Python is a programming concept that hides complex implementation details while exposing only essential information and functionalities to users. • In Python, we can achieve data abstraction by using abstract classes and abstract classes can be created using abc (abstract base class) module @abstractmethod of abc module. 68
  • 69. Dr. A. B. Shinde Data Abstraction in Python • Abstraction classes in Python • Abstract class is a class in which one or more abstract methods are defined. When a method is declared inside the class without its implementation is known as abstract method. • Abstract Method: This feature is not a default feature. • To create abstract method and abstract classes we have to import the "ABC" and "abstractmethod" classes from abc (Abstract Base Class) library. • Abstract method of base class force its child class to write the implementation of the all abstract methods defined in base class. 69
  • 70. Dr. A. B. Shinde Data Abstraction in Python • Abstraction classes in Python • Abstract Method: Abstract methods are methods that are defined in an abstract class but do not have an implementation. They serve as a blueprint for the subclasses, ensuring that they provide their own implementation. 70
  • 71. Dr. A. B. Shinde Data Abstraction in Python • Abstraction classes in Python • Concrete Method: Concrete methods are the methods defined in an abstract base class with their complete implementation. • Concrete methods are required to avoid replication of code in subclasses. • For example: In abstract base class there may be a method that implementation is to be same in all its subclasses, so we write the implementation of that method in abstract base class after which we do not need to write implementation of the concrete method again and again in every subclass. 71
  • 72. Dr. A. B. Shinde Data Abstraction in Python • Abstraction classes in Python • Concrete methods are methods that have full implementations in an abstract class. • These methods can be inherited by subclasses and used directly without needing to be redefined. 72
  • 73. Exception Handling in Python Dr. A. B. Shinde
  • 74. Dr. A. B. Shinde Python Exception Handling • Python Exception Handling handles errors that occur during the execution of a program. • Exception handling allows to respond to the error, instead of crashing the running program. • It enables you to catch and manage errors, making your code more robust and user-friendly. • Example: 74
  • 75. Dr. A. B. Shinde Python Exception Handling • Difference Between Exception and Error • Error: Errors are serious issues that a program should not try to handle. • They are usually problems in the code's logic or configuration and need to be fixed by the programmer. • Examples include syntax errors and memory errors. • Exception: Exceptions are less severe than errors and can be handled by the program. • They occur due to situations like invalid input, missing files or network issues. 75
  • 76. Dr. A. B. Shinde Python Exception Handling • try, except, else and finally Blocks: • try Block: test a block of code for errors. Python will "try" to execute the code in this block. If an exception occurs, execution will immediately jump to the except block. • except Block: It enables us to handle the error or exception. If the code inside the try block throws an error, Python jumps to the except block and executes it. • else Block: It is optional and if included, must follow all except blocks. The else block runs only if no exceptions are raised in the try block. • finally Block: It always runs, regardless of whether an exception occurred or not. It is typically used for cleanup operations (closing files, releasing resources). 76
  • 77. Dr. A. B. Shinde Python Exception Handling • try, except, else and finally Blocks: 77
  • 78. Dr. A. B. Shinde Python Exception Handling • Common Exceptions in Python: 78 Exception Name Description BaseException The base class for all built-in exceptions. Exception The base class for all non-exit exceptions. ArithmeticError Base class for all errors related to arithmetic operations. ZeroDivisionError Raised when a division or modulo operation is performed with zero as the divisor. OverflowError Raised when a numerical operation exceeds the maximum limit of a data type. FloatingPointError Raised when a floating-point operation fails. AssertionError Raised when an assert statement fails. AttributeError Raised when an attribute reference or assignment fails. IndexError Raised when a sequence subscript is out of range. KeyError Raised when a dictionary key is not found. Exception Name Description MemoryError Raised when an operation runs out of memory. NameError Raised when a local or global name is not found. OSError Raised when a system-related operation (like file I/O) fails. TypeError Raised when an operation or function is applied to an object of inappropriate type. ValueError Raised when a function receives an argument of the right type but inappropriate value. ImportError Raised when an import statement has issues. ModuleNotFoundError Raised when a module cannot be found.
  • 79. Dr. A. B. Shinde Python Exception Handling • Raise an Exception: • We raise an exception in Python using the raise keyword followed by an instance of the exception class that we want to trigger. • We can choose from built-in exceptions or define our own custom exceptions by inheriting from Python's built-in Exception class. 79
  • 80. Dr. A. B. Shinde Python Exception Handling • Advantages of Exception Handling: • Improved program reliability: By handling exceptions properly, you can prevent your program from crashing or producing incorrect results due to unexpected errors or input. • Simplified error handling: Exception handling allows you to separate error handling code from the main program logic, making it easier to read and maintain your code. • Cleaner code: With exception handling, you can avoid using complex conditional statements to check for errors, leading to cleaner and more readable code. • Easier debugging: When an exception is raised, the Python interpreter prints a traceback that shows the exact location where the exception occurred, making it easier to debug your code. 80
  • 81. Dr. A. B. Shinde Python Exception Handling • Disadvantages of Exception Handling: • Performance overhead: Exception handling can be slower than using conditional statements to check for errors, as the interpreter has to perform additional work to catch and handle the exception. • Increased code complexity: Exception handling can make your code more complex, especially if you have to handle multiple types of exceptions or implement complex error handling logic. • Possible security risks: Improperly handled exceptions can potentially reveal sensitive information or create security vulnerabilities in your code, so it's important to handle exceptions carefully and avoid exposing too much information about your program. 81
  • 82. 82 This presentation is published only for educational purpose Thank You… [email protected]