KEMBAR78
Object Oriented Programming in Python.pptx
Prof.Shinde S.A. 1
Unit IV-Object Oriented Programming in Python
Prof.Shinde S.A. 2
Object Oriented Concepts
• Python is an object-oriented programming language. It allows
us to develop applications using an Object Oriented
approach. In Python, we can easily create and use classes and
objects.
• Major principles of object-oriented programming system
1) Object
2) Class
3) Method
4) Inheritance
5) Polymorphism
6) Data Abstraction
7) Encapsulation
Prof.Shinde S.A. 3
class
• The class can be defined as a collection of objects. It
is a logical entity that has some specific attributes
and methods. For example: if you have an
employee class then it should contain an attribute
and method, i.e. an email id, name, age, salary, etc.
• Syntax
• class ClassName:
• <statement-1>
• .
• .
• <statement-N>
Prof.Shinde S.A. 5
Syntax for creating a Class
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).
# define a class
class Dog:
sound = "bark" # class attribute
Prof.Shinde S.A. 6
Syntax for Create Object
• An Object is an instance of a Class. It represents a specific
implementation of the class and holds its own data.
• Now, let’s create an object from Dog class.
• Example-
class Dog:
sound = "bark"
# Create an object from the class
dog1 = Dog()
# Access the class attribute Output-
print(dog1.sound) bark
Prof.Shinde S.A. 7
The __init__() Function
• All classes have a function called __init__(), which is always executed when the class
is being initiated.
• Use the __init__() function to assign values to object properties, or other operations
that are necessary to do when the object is being created.
• Note: The __init__() function is called automatically every time the class is being
used to create a new object.
• Note: The self parameter is a reference to the current instance of the class, and is
used to access variables that belong to the class.
• Example-
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person(“Raya", 30) Output-
print(p1.name) Raya
print(p1.age) 30
__init__ method: Initializes the name and age attributes when a new object is created.
Prof.Shinde S.A. 8
Python - Constructors
• Python constructor is an instance method in a class, that is
automatically called whenever a new object of the class is
created.
• The name of the constructor method is always __init__.
• Python uses a special method called __init__() to initialize
the instance variables for the object, as soon as it is
declared.
• Creating a constructor in Python
• The __init__() method acts as a constructor. It needs a
mandatory argument named self, which is the reference to
the object.
• def __init__(self, parameters):
Prof.Shinde S.A. 9
Types of Constructor in Python
• Python has two types of constructor −
• Default Constructor
• Parameterized Constructor
• Default Constructor: A default constructor is a
constructor that takes no arguments. It is used to
create an object with default values for its attributes.
• Parameterized Constructor: A parameterized
constructor is a constructor that takes one or more
arguments. It is used to create an object with custom
values for its attributes.
Prof.Shinde S.A. 10
• Here is an example of a default constructor:
class Person:
def __init__(self):
self.name = “Riyansh“
self.age = 3
person = Person() Output:
print(person.name) Riyansh
print(person.age) 3
In this example, the __init__ method is the default constructor for
the Person class. It is called automatically when the object is
created, and it sets the default values for
the name and age attributes.
Prof.Shinde S.A. 11
• Here is an example of a class with a
parameterized constructor:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Riyansh", 3)
print(person.name)
print(person.age)
Prof.Shinde S.A. 12
Non-Parameterized Constructors
• There is not necessarily a need for a non-parameterized constructor in Python. It is up to the
programmer to decide whether to include a non-parameterized constructor in a class.
• However, a non-parameterized constructor can be useful
1.When you want to initialize the default values for the instance variables of an object.
2. When you want to perform some operations when an object is created, such as opening a
file or establishing a connection to a database.
• Example-
class MyClass:
def __init__(self): Output-
self.arg1 = 10 10
self.arg2 = 2020
obj = MyClass()
print(obj.arg1)
print(obj.arg2)
Prof.Shinde S.A. 13
the self parameter
Self represents the instance of the class.
By using the “self” we can access the attributes and methods of
the class in Python.
It is customary to use “self” as the first parameter in instance
methods of a class. 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.
Prof.Shinde S.A. 14
Destructors in Python
Destructors are called when an object gets destroyed.
The __del__() method is a known as a destructor method in Python. It is called
when all references to the object have been deleted i.e when an object is garbage
collected.
Syntax of destructor declaration :
def __del__(self):
# body of destructor
Example-
class Employee:
def __init__(self):
print('Employee created.')
def __del__(self):
print('Destructor called, Employee deleted.')
obj = Employee()
del obj
Output-
Employee created.
Destructor called, Employee deleted.
Prof.Shinde S.A. 15
Polymorphism
• Polymorphism contains two words "poly" and "morphs".
Poly means many and Morphs means form, shape.
• By polymorphism, we understand that one task can be
performed in different ways.
• For example You have a class animal, and all animals
speak. But they speak differently. Here, the "speak"
behavior is polymorphic in the sense and depends on the
animal. So, the abstract "animal" concept does not
actually "speak", but specific animals (like dogs and
cats) have a concrete implementation of the action
"speak".
Prof.Shinde S.A. 16
Polymorphism
Ways of implementing Polymorphism in Python
There are four ways to implement polymorphism in Python −
Duck Typing
Operator Overloading
Method Overriding
Method Overloading
Prof.Shinde S.A. 17
Types of Polymorphism
1.Compile-time Polymorphism
2.Runtime 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.
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.
Prof.Shinde S.A. 18
Method Overloading
•Two or more methods have the same name but different numbers of parameters or
different types of parameters, or both. These methods are called overloaded methods
and this is called method overloading.
•Like other languages (for example method overloading in C++) do, python does not
supports method overloading. We may overload the methods but can only use the
latest defined method.
def add(a, b):
p = a + b
print(p)
def add(a, b, c):
p = a + b + c
print(p)
# Uncommenting the below line shows an error
#add(4, 5) Output
# This line will call the second add method 14
add(4, 5, 5)
Prof.Shinde S.A. 19
To overcome the above problem we can use different ways to
achieve the method overloading.
1.Implement Method Overloading Using MultipleDispatch
First, you need to install the Multipledispatch module using the
following command −
pip install multipledispatch
from multipledispatch import dispatch
@dispatch(int, int)
def add(first, second):
result = first+second
print(result)
@dispatch(int, int, int)
def add(first, second, third):
result = first + second + third
print(result)
add(2, 3) # this will give output of 5
add(2, 3, 2) # this will give output of 7
Prof.Shinde S.A. 20
2.Implement Method Overloading Using Variable-length
Output-
Prof.Shinde S.A. 21
Method Overriding in Python
The Python method overriding refers to defining a method in a subclass with the
same name as a method in its superclass. In this case, the Python interpreter
determines which method to call at runtime based on the actual object being
referred to.
Example-
Output-
Prof.Shinde S.A. 22
Data Hiding / Abstraction
abstraction and data hiding are two important concepts. Abstraction is a process of
extracting important information without involving the complete detail of the system.
On the other hand, data hiding is a process of wrapping the data in a single unit, i.e., to
achieve data encapsulation.
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.
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: In Python, abstract method 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.
Prof.Shinde S.A. 23
Data hiding can be achieved using access specifiers, such as 'private',
and 'protected'. It acts like a security layer as it ensures that users cannot access
internal data without authentication.
In python, if we want to hide any variable, then we have to use the double
underscore() before the variable name. This makes the class members
inaccessible and private to other classes.
__variablename
Public
When a member of a class is "public," it means it can be accessed by other
objects.
Private
When members of the class are private, they can only be accessed by objects of
the same class. We use double underscores (__) before the data member to
create a private data member inside the class.
Protected
Protected means the member of a class is only accessible by its inherited or
child class. To create a protected data member inside the class, we use a single
underscore (_) before the data member.
Prof.Shinde S.A. 24
Example
Prof.Shinde S.A. 25
Inheritance
• Inheritance is the most important aspect of object-oriented
programming which simulates the real world concept of inheritance.
It specifies that the child object acquires all the properties and
behaviors of the parent object.
• Example : Father-child , Shape-triangle,square
• The newly created class is known as the subclass (child or derived
class).
• The existing class from which the child class inherits is known as the
superclass (parent or base class).
• It provides re-usability of the code.
Prof.Shinde S.A. 26
Types of Inheritance
In Python, inheritance can be divided in five different categories −
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
Prof.Shinde S.A. 27
Single Inheritance
This is the simplest form of inheritance where a child class inherits
attributes and methods from only one parent class.
Output-
Prof.Shinde S.A. 28
Multiple Inheritance
Multiple inheritance in Python allows you to construct a class
based on more than one parent classes. The Child class thus
inherits the attributes and method from all parents. The child
can override methods inherited from any parent.
Syntax-
class parent1:
#statements
class parent2:
#statements
class child(parent1, parent2):
#statements
Prof.Shinde S.A. 29
Example-
Output-
Prof.Shinde S.A. 30
Multilevel Inheritance
In multilevel inheritance, a class is derived from another
derived class. There exists multiple layers of inheritance. We
can imagine it as a grandparent-parent-child relationship.
Syntax-
class SuperClass:
# Super class code here
class DerivedClass1(SuperClass):
# Derived class 1 code here
class DerivedClass2(DerivedClass1):
# Derived class 2 code here
Prof.Shinde S.A. 31
Example-
Output-

Object Oriented Programming in Python.pptx

  • 1.
    Prof.Shinde S.A. 1 UnitIV-Object Oriented Programming in Python
  • 2.
    Prof.Shinde S.A. 2 ObjectOriented Concepts • Python is an object-oriented programming language. It allows us to develop applications using an Object Oriented approach. In Python, we can easily create and use classes and objects. • Major principles of object-oriented programming system 1) Object 2) Class 3) Method 4) Inheritance 5) Polymorphism 6) Data Abstraction 7) Encapsulation
  • 3.
    Prof.Shinde S.A. 3 class •The class can be defined as a collection of objects. It is a logical entity that has some specific attributes and methods. For example: if you have an employee class then it should contain an attribute and method, i.e. an email id, name, age, salary, etc. • Syntax • class ClassName: • <statement-1> • . • . • <statement-N>
  • 4.
    Prof.Shinde S.A. 5 Syntaxfor creating a Class 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). # define a class class Dog: sound = "bark" # class attribute
  • 5.
    Prof.Shinde S.A. 6 Syntaxfor Create Object • An Object is an instance of a Class. It represents a specific implementation of the class and holds its own data. • Now, let’s create an object from Dog class. • Example- class Dog: sound = "bark" # Create an object from the class dog1 = Dog() # Access the class attribute Output- print(dog1.sound) bark
  • 6.
    Prof.Shinde S.A. 7 The__init__() Function • All classes have a function called __init__(), which is always executed when the class is being initiated. • Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created. • Note: The __init__() function is called automatically every time the class is being used to create a new object. • Note: The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class. • Example- class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person(“Raya", 30) Output- print(p1.name) Raya print(p1.age) 30 __init__ method: Initializes the name and age attributes when a new object is created.
  • 7.
    Prof.Shinde S.A. 8 Python- Constructors • Python constructor is an instance method in a class, that is automatically called whenever a new object of the class is created. • The name of the constructor method is always __init__. • Python uses a special method called __init__() to initialize the instance variables for the object, as soon as it is declared. • Creating a constructor in Python • The __init__() method acts as a constructor. It needs a mandatory argument named self, which is the reference to the object. • def __init__(self, parameters):
  • 8.
    Prof.Shinde S.A. 9 Typesof Constructor in Python • Python has two types of constructor − • Default Constructor • Parameterized Constructor • Default Constructor: A default constructor is a constructor that takes no arguments. It is used to create an object with default values for its attributes. • Parameterized Constructor: A parameterized constructor is a constructor that takes one or more arguments. It is used to create an object with custom values for its attributes.
  • 9.
    Prof.Shinde S.A. 10 •Here is an example of a default constructor: class Person: def __init__(self): self.name = “Riyansh“ self.age = 3 person = Person() Output: print(person.name) Riyansh print(person.age) 3 In this example, the __init__ method is the default constructor for the Person class. It is called automatically when the object is created, and it sets the default values for the name and age attributes.
  • 10.
    Prof.Shinde S.A. 11 •Here is an example of a class with a parameterized constructor: class Person: def __init__(self, name, age): self.name = name self.age = age person = Person("Riyansh", 3) print(person.name) print(person.age)
  • 11.
    Prof.Shinde S.A. 12 Non-ParameterizedConstructors • There is not necessarily a need for a non-parameterized constructor in Python. It is up to the programmer to decide whether to include a non-parameterized constructor in a class. • However, a non-parameterized constructor can be useful 1.When you want to initialize the default values for the instance variables of an object. 2. When you want to perform some operations when an object is created, such as opening a file or establishing a connection to a database. • Example- class MyClass: def __init__(self): Output- self.arg1 = 10 10 self.arg2 = 2020 obj = MyClass() print(obj.arg1) print(obj.arg2)
  • 12.
    Prof.Shinde S.A. 13 theself parameter Self represents the instance of the class. By using the “self” we can access the attributes and methods of the class in Python. It is customary to use “self” as the first parameter in instance methods of a class. 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.
  • 13.
    Prof.Shinde S.A. 14 Destructorsin Python Destructors are called when an object gets destroyed. The __del__() method is a known as a destructor method in Python. It is called when all references to the object have been deleted i.e when an object is garbage collected. Syntax of destructor declaration : def __del__(self): # body of destructor Example- class Employee: def __init__(self): print('Employee created.') def __del__(self): print('Destructor called, Employee deleted.') obj = Employee() del obj Output- Employee created. Destructor called, Employee deleted.
  • 14.
    Prof.Shinde S.A. 15 Polymorphism •Polymorphism contains two words "poly" and "morphs". Poly means many and Morphs means form, shape. • By polymorphism, we understand that one task can be performed in different ways. • For example You have a class animal, and all animals speak. But they speak differently. Here, the "speak" behavior is polymorphic in the sense and depends on the animal. So, the abstract "animal" concept does not actually "speak", but specific animals (like dogs and cats) have a concrete implementation of the action "speak".
  • 15.
    Prof.Shinde S.A. 16 Polymorphism Waysof implementing Polymorphism in Python There are four ways to implement polymorphism in Python − Duck Typing Operator Overloading Method Overriding Method Overloading
  • 16.
    Prof.Shinde S.A. 17 Typesof Polymorphism 1.Compile-time Polymorphism 2.Runtime 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. 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.
  • 17.
    Prof.Shinde S.A. 18 MethodOverloading •Two or more methods have the same name but different numbers of parameters or different types of parameters, or both. These methods are called overloaded methods and this is called method overloading. •Like other languages (for example method overloading in C++) do, python does not supports method overloading. We may overload the methods but can only use the latest defined method. def add(a, b): p = a + b print(p) def add(a, b, c): p = a + b + c print(p) # Uncommenting the below line shows an error #add(4, 5) Output # This line will call the second add method 14 add(4, 5, 5)
  • 18.
    Prof.Shinde S.A. 19 Toovercome the above problem we can use different ways to achieve the method overloading. 1.Implement Method Overloading Using MultipleDispatch First, you need to install the Multipledispatch module using the following command − pip install multipledispatch from multipledispatch import dispatch @dispatch(int, int) def add(first, second): result = first+second print(result) @dispatch(int, int, int) def add(first, second, third): result = first + second + third print(result) add(2, 3) # this will give output of 5 add(2, 3, 2) # this will give output of 7
  • 19.
    Prof.Shinde S.A. 20 2.ImplementMethod Overloading Using Variable-length Output-
  • 20.
    Prof.Shinde S.A. 21 MethodOverriding in Python The Python method overriding refers to defining a method in a subclass with the same name as a method in its superclass. In this case, the Python interpreter determines which method to call at runtime based on the actual object being referred to. Example- Output-
  • 21.
    Prof.Shinde S.A. 22 DataHiding / Abstraction abstraction and data hiding are two important concepts. Abstraction is a process of extracting important information without involving the complete detail of the system. On the other hand, data hiding is a process of wrapping the data in a single unit, i.e., to achieve data encapsulation. 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. 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: In Python, abstract method 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.
  • 22.
    Prof.Shinde S.A. 23 Datahiding can be achieved using access specifiers, such as 'private', and 'protected'. It acts like a security layer as it ensures that users cannot access internal data without authentication. In python, if we want to hide any variable, then we have to use the double underscore() before the variable name. This makes the class members inaccessible and private to other classes. __variablename Public When a member of a class is "public," it means it can be accessed by other objects. Private When members of the class are private, they can only be accessed by objects of the same class. We use double underscores (__) before the data member to create a private data member inside the class. Protected Protected means the member of a class is only accessible by its inherited or child class. To create a protected data member inside the class, we use a single underscore (_) before the data member.
  • 23.
  • 24.
    Prof.Shinde S.A. 25 Inheritance •Inheritance is the most important aspect of object-oriented programming which simulates the real world concept of inheritance. It specifies that the child object acquires all the properties and behaviors of the parent object. • Example : Father-child , Shape-triangle,square • The newly created class is known as the subclass (child or derived class). • The existing class from which the child class inherits is known as the superclass (parent or base class). • It provides re-usability of the code.
  • 25.
    Prof.Shinde S.A. 26 Typesof Inheritance In Python, inheritance can be divided in five different categories − 1. Single Inheritance 2. Multiple Inheritance 3. Multilevel Inheritance 4. Hierarchical Inheritance 5. Hybrid Inheritance
  • 26.
    Prof.Shinde S.A. 27 SingleInheritance This is the simplest form of inheritance where a child class inherits attributes and methods from only one parent class. Output-
  • 27.
    Prof.Shinde S.A. 28 MultipleInheritance Multiple inheritance in Python allows you to construct a class based on more than one parent classes. The Child class thus inherits the attributes and method from all parents. The child can override methods inherited from any parent. Syntax- class parent1: #statements class parent2: #statements class child(parent1, parent2): #statements
  • 28.
  • 29.
    Prof.Shinde S.A. 30 MultilevelInheritance In multilevel inheritance, a class is derived from another derived class. There exists multiple layers of inheritance. We can imagine it as a grandparent-parent-child relationship. Syntax- class SuperClass: # Super class code here class DerivedClass1(SuperClass): # Derived class 1 code here class DerivedClass2(DerivedClass1): # Derived class 2 code here
  • 30.