0% found this document useful (0 votes)
15 views142 pages

Unit 2 DS Basics of OOP Concepts

Uploaded by

wohak23915
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views142 pages

Unit 2 DS Basics of OOP Concepts

Uploaded by

wohak23915
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 142

Basics of Object

Oriented Programming
PREPARED AND COMPILED BY:
D.R. GANDHI
LECTURER IN INFORMATION TECHNOLOGY
Learning Outcomes:
 Oops Concepts
 Class and Object
 Constructors
 Types of methods
 Instance method
 Class method
 static method
 Data Encapsulation
 Inheritance - single, multiple, multi-level, hierarchical, hybrid
 Polymorphism through inheritance
 Abstraction - abstract class
Procedural Programming:

 It is defined as a programming language derived from the structure


programming and based on calling procedures.
 The procedures are the functions, routines, or subroutines that consist of
the computational steps required to be carried.
 It follows a step-by-step approach in order to break down a task into a set
of variables and routines via a sequence of instructions.
Procedural Programming:

 Example of make lemonade:-


 The procedure of making lemonade involves- first taking water according to
the need, then adding sugar to the water, then adding lemon juice to the
mixture, and finally mixing the whole solution. And your lemonade is ready
to serve.
 In a similar way, POP requires a certain procedure of steps. A procedural
program consists of functions.
 This means that in the POP approach the program is divided into functions,
which are specific to different tasks.
 These functions are arranged in a specific sequence and the control of the
program flows sequentially.
 Procedural programming follows a top-down approach during the designing
of a program.
Object oriented Programming:

 Object-Oriented Programming(OOP), is all about creating “objects”.


 An object is a group of interrelated variables and functions.
 These variables are often referred to as properties of the object and
functions are referred to as the behavior of the objects. These objects
provide a better and clear structure for the program.
 It is well suited for programs that are large, complex, and actively updated
or maintained.
Object oriented Programming:

 For example, a car can be an object.


 If we consider the car as an object then its properties would be – its color,
its model, its price, its brand, etc. And its behavior/function would be
acceleration, slowing down, gear change.
 For example, a dog can be an object.
 If we consider a dog as an object then its properties would be- his color, his
breed, his name, his weight, etc. And his behavior/function would be
walking, barking, playing, etc.
 Object-Oriented programming is famous because it implements the real-
world entities like objects, hiding, inheritance, etc in programming. It
makes visualization easier because it is close to real-world scenarios
Pop vs. oop:
Procedural Programming Object-oriented Programming

Procedural programming uses a list of Object-oriented programming is the problem-


instructions to do computation step by step. solving approach and used where
computation is done by using objects.
It is not easy to maintain the codes when the It makes the development and maintenance
project becomes lengthy. easier.
It doesn't simulate the real world. It works on It simulates the real world entity. So real-
step by step instructions divided into small world problems can be easily solved through
parts called functions. oops.
Procedural language doesn't provide any It provides data hiding. So it is more secure
proper way for data binding, so it is less than procedural languages. You cannot
secure. access private data from anywhere.
It follows a top-down approach. It follows a bottom-up approach.

Example of procedural languages are: C, Example of object-oriented programming


Fortran, Pascal, VB etc. languages is C++, Java, .Net, Python, C#, etc.
OOP Concepts

 Class
 Objects
 Polymorphism
 Encapsulation
 Inheritance
 Data Abstraction
OOP Concepts

 Class:-
 The class can be defined as a collection of objects.
 It is a logical entity that has some specific attributes and methods.
 A class is a blueprint for the object.
 To create an object we require a model or plan or blueprint which is nothing
but class.
 A class contains the properties (attribute) and action (behavior) of the
object.
 Properties represent variables, and the methods represent actions. Hence
class includes both variables and methods.
OOP Concepts
 Object:-
 Object is an instance of a class.
 The physical existence of a class is nothing but an object.
 In other words, the object is an entity that has a state and behavior.
 It may be any real-world object like the mouse, keyboard, laptop, etc.
OOP Concepts

 Objects have two characteristics: They have states and behaviors (object
has attributes and methods attached to it) Attributes represent its state,
and methods represent its behavior. Using its methods, we can modify its
state.
 In short, Every object has the following property.
 Identity: Every object must be uniquely identified.
 State: An object has an attribute that represents a state of an object, and it
also reflects the property of an object.
 Behavior: An object has methods that represent its behavior.
OOP Concepts

 Python is an Object-Oriented Programming language, so everything in


Python is treated as an object.
 An object is a real-life entity.
 It is the collection of various data and functions that operate on those data.
 For example, If we design a class based on the states and behaviors of a
Person, then States can be represented as instance variables and behaviors
as class methods.
OOP Concepts
OOP Concepts
 A real-life example of class and objects.
 Class: Person  objects are created from the
same class, but they have
 State: Name, Sex, Profession different states and
 Behavior: Working, Study behaviors.
 Object 1: Jessa  Object 2: Jon
 State:  State:
 Name: Jessa  Name: Jon
 Sex: Female  Sex: Male
 Profession: Software Engineer  Profession: Doctor
 Behavior:  Behavior:
 Working: She is working as a software  Working: He is working as a doctor
developer at ABC Company
 Study: He studies 5 hours a day
 Study: She studies 2 hours a day
OOP Concepts
 Create a Class in Python:
 In Python, class is defined by using the class keyword.
 Syntax:
class class_name:
'''This is a docstring. I have created a new class'''
<statement 1>
………
<statement N>
 class_name: It is the name of the class
 Docstring: It is the first string inside the class and has a brief description of the
class. Although not mandatory, this is highly recommended.
 statements: Attributes and methods
OOP Concepts
Example:-
class car:
def __init__(self,modelname, year):
# data members (instance variables)
self.modelname = modelname Syntax to create object:-
self.year = year <object-name> = <class-name>(<arguments>)

# Behavior (instance methods)


def display(self):
print(self.modelname,self.year)
c1 = car("Toyota", 2016)
c1.display()
OOP Concepts
 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.
 By using inheritance, we can create a class which uses all the properties
and behavior of another class.
 The new class is known as a derived class or child class, and the one whose
properties are acquired is known as a base class or parent class.
 It provides the re-usability of the code.
OOP Concepts
 Inheritance:-
OOP Concepts
 Polymorphism:-
 Polymorphism contains two words "poly" and "morphs".
 Poly means many, and morph means 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 a 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".
OOP Concepts
 Polymorphism:-
OOP Concepts
 Encapsulation:-
 Encapsulation is also an essential aspect of object-oriented programming.
 It is used to restrict access to methods and variables.
 In encapsulation, code and data are wrapped together within a single unit
from being modified by accident.
OOP Concepts
 Abstraction:-
 Data abstraction and encapsulation both are often used as synonyms.
 Both are nearly synonyms because data abstraction is achieved through
encapsulation.
 Abstraction is used to hide internal details and show only functionalities.
 Abstracting something means to give names to things so that the name
captures the core of what a function or a whole program does.
_init_()
class Human:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
 The properties that all Human objects must have, are defined in a method
called init(). Every time a new Human object is created, __init__() sets the
initial state of the object by assigning the values of we provide inside the
object’s properties. That is, __init__() initializes each new instance of the
class.
 __init__() can take any number of parameters, but the first parameter is
always a variable called self.
 The self parameter is a reference to the current instance of the class. It
means, the self parameter points to the address of the current object of a
class, allowing us to access the data of its(the object's) variables.
Example:
Name: Jessa Gender: Female Profession:
Software Engineer
name of Person: Jessa
Gender of a person : Female
Person is working as a: Software Engineer
Constructor:
 In object-oriented programming, A constructor is a special method used to create
and initialize an object of a class. This method is defined in the class.
 The constructor is executed automatically at the time of object creation.
 The primary use of a constructor is to declare and initialize data member/ instance
variables of a class. The constructor contains a collection of statements (i.e.,
instructions) that executes at the time of object creation to initialize the attributes of
an object.
 For example, when we execute obj = Sample(), Python gets to know that obj is an
object of class Sample and calls the constructor of that class to create an object.
 In Python, Object creation is divided into two parts in Object Creation and Object
initialization.
 Internally, the __new__ is the method that creates the object
 the __init__() method we can implement constructor to initialize the object.
Constructor:

 Syntax of a constructor:-
def __init__(self):
# body of the constructor
 def: The keyword is used to define function.
 __init__() Method: It is a reserved method. This method gets called as soon as an
object of a class is instantiated.
 self: The first argument self refers to the current object. It binds the instance to the
__init__() method. It’s usually named self to follow the naming convention.
 Note: The __init__() method arguments are optional. We can define a constructor
with any number of arguments.
Example: Create a Constructor in Python

Inside Constructor
All variables initialized
Hello, my name is Emma
Constructor:

 Note:
 For every object, the constructor will be executed only once. For example, if we
create four objects, the constructor is called four times.
 In Python, every class has a constructor, but it’s not required to define it explicitly.
Defining constructors in class is optional.
 Python will provide a default constructor if no constructor is defined.
Constructor:
 Types of Constructors:-
 In Python, we have the following three types of constructors.
 Default Constructor
 Non-parametrized constructor
 Parameterized constructor
Constructor:
 Default Constructor:-
 Python will provide a default constructor if no constructor is defined. Python adds a
default constructor when we do not include the constructor in the class or forget to
declare it. It does not perform any task but initializes the objects. It is an empty
constructor without a body.
 If you do not implement any constructor in your class or forget to declare it, the Python
inserts a default constructor into your code on your behalf. This constructor is known
as the default constructor.
 It does not perform any task but initializes the objects. It is an empty constructor
without a body.
 Note:
 If you implement your constructor, then the default constructor will not be added.
Constructor:

Output:
Inside Display
Constructor:

 Non-Parametrized Constructor:-
 A constructor without any arguments is called a non-parameterized constructor.
This type of constructor is used to initialize each object with default values.
 This constructor doesn’t accept the arguments during object creation.
 Instead, it initializes every object with the same set of values.
Constructor:

Name: PYnative Address: ABC Street


Constructor:

 Parameterized Constructor:-
 A constructor with defined parameters or arguments is called a parameterized
constructor. We can pass different values to each object at the time of creation using
a parameterized constructor.
 The first parameter to constructor is self that is a reference to the being constructed,
and the rest of the arguments are provided by the programmer. A parameterized
constructor can have any number of arguments.
 For example, consider a company that contains thousands of employees. In this
case, while creating each employee object, we need to pass a different name, age,
and salary. In such cases, use the parameterized constructor.
Constructor:

Emma 23 7500
Kelly 25 8500
Constructor:

 Constructor With Default Values:-


 Python allows us to define a constructor with default values. The default value will
be used if we do not pass arguments to the constructor at the time of object creation.
Constructor:

Emma 12 7
Kelly 13 7
Class Attributes

 When we design a class, we use instance variables and class variables.


 In Class, attributes can be defined into two parts:
 Instance variables: The instance variables are attributes attached to an instance of
a class.
 We define instance variables in the constructor ( the __init__() method of a class).
 Class Variables: A class variable is a variable that is declared inside of class, but
outside of any instance method or __init__() method.
Class Attributes
Class Attributes

 Objects do not share instance attributes.


 Instead, every object has its copy of the instance attribute and is unique to each
object.
 All instances of a class share the class variables. However, unlike instance variables,
the value of a class variable is not varied from object to object.
 Only one copy of the static variable will be created and shared between all objects of
the class.
 Accessing properties and assigning values:-
 An instance attribute can be accessed or modified by using the dot notation:
instance_name.attribute_name.
 A class variable is accessed or modified using the class name
Class Attributes
Example

 Define a Book class with the following attributes: Title, Author (Full name),Price.
 Define a constructor used to initialize the attributes of the method with values
entered by the user.
 Set the View() method to display information for the current book.
Example

Enter Title of book: DS with python


Enter Author name of the book: Dhaval
Gandhi
Enter Price of book:250
Name of book is: DS with python
Name of author is: Dhaval Gandhi
Name of price is: 250.0
Class Methods

 In Object-oriented programming, Inside a Class, we can define the following three


types of methods.
 Instance method: Used to access or modify the object state. If we use instance
variables inside a method, such methods are called instance methods.
 Class method: Used to access or modify the class state. In method implementation,
if we use only class variables, then such type of methods we should declare as a
class method.
 Static method: It is a general utility method that performs a task in isolation. Inside
this method, we don’t use instance or class variable because this static method
doesn’t have access to the class attributes.
Class Methods
Instance Method:

 If we use instance variables inside a method, such methods are called instance
methods.
 The instance method performs a set of actions on the data/value provided by the
instance variables.
 A instance method is bound to the object of the class.
 It can access or modify the object state by changing the value of a instance variables
 When we create a class in Python, instance methods are used regularly. To work
with an instance method, we use the self keyword.
 We use the self keyword as the first parameter to a method. The self refers to the
current object.
 Any method we create in a class will automatically be created as an instance method
unless we explicitly tell Python that it is a class or static method.
Instance Method:
Instance Method:

First Student
Name: Jessa Age: 14

Second Student
Name: Kelly Age: 16
Instance Method:

 Notes:
 Inside any instance method, we can use self to access any data or method that
reside in our class. We are unable to access it without a self parameter.
 An instance method can freely access attributes and even modify the value of
attributes of an object by using the self parameter.
 By Using self.__class__ attribute we can access the class attributes and change the
class state. Therefore instance method gives us control of changing the object as well
as the class state.
Instance Method:

 Instance method has two types:


 Accessor method:-
 It simply access or read data of the variables. They do not modify the data in the
variables.
def getname(self)
return self.name
 Mutator method:-
 It not only read the data but also modify them.
def getname(self)
return self.name=name
Instance Method:

class VIII
Roll Number: 20 Name: Emma Age: 14
class IX
Roll Number: 35 Name: Emma Age: 15
Create Instance Variables in
Instance Method:
 Till the time we used constructor to create instance attributes.
 instance attributes are not specific only to the __init__() method; they can be defined
elsewhere in the class.
Create Instance Variables in
Instance Method:
Roll Number: 20 Name: Emma Age: 14 Marks: 75
Class Method:
 Class methods are methods that are called on the class itself, not on a specific object
instance. Therefore, it belongs to a class level, and all class instances share a class
method.
 A class method is bound to the class and not the object of the class. It can access
only class variables.
 It can modify the class state by changing the value of a class variable that would
apply across all the class objects.
 In method implementation, if we use only class variables, we should declare such
methods as class methods. The class method has a cls as the first parameter, which
refers to the class.
 The class method can be called using ClassName.method_name() as well as by
using an object of the class.
Create Class Method Using
@classmethod Decorator
 We must explicitly tell Python that it is a class method using the @classmethod
decorator or classmethod() function.
 Class methods are defined inside a class, and it is pretty similar to defining a regular
function.
 inside the class method, we use the cls keyword as a first parameter to access class
variables. Therefore the class method gives us control of changing the class state.
 The class method can only access the class attributes, not the instance attributes.
 Class methods are used when we are dealing with factory methods. Factory
methods are those methods that return a class object for different use cases.
Thus, factory methods create concrete implementations of a common interface.
Class Method:
Jessa's age is: 20
Joy's age is: 27
Create Class Method Using
@classmethod Decorator
 To make a method as class method, add @classmethod decorator before the method
definition, and add cls as the first parameter to the method.
 The @classmethod decorator is a built-in function decorator. In Python, we use the
@classmethod decorator to declare a method as a class method. The @classmethod
decorator is an expression that gets evaluated after our function is defined.
 The @classmethod decorator is used for converting calculate_age() method to a class
method.
 The calculate_age() method takes Student class (cls) as a first parameter and returns
constructor by calling Student(name, date.today().year - birthYear), which is
equivalent to Student(name, age)
Create Class Method Using
classmethod() function
 Apart from a decorator, the built-in function classmethod() is used to convert a
normal method into a class method.
 The classmethod() is an inbuilt function in Python, which returns a class method for
a given function.
 Syntax:
 classmethod(function)
 function: It is the name of the method you want to convert as a class method.
 It returns the converted class method.
 A classmethod() function is the older way to create the class method in Python. In a
newer version of Python, we should use the @classmethod decorator to create a class
method.
Create Class Method Using
classmethod() function

School Name is : ABC School


Create Class Method Using
classmethod() function
Jessa 20 School: ABC School
Jessa 20 School: XYZ School
Create Class Method Using
classmethod() function

Student: Harry 12 ABC School


Student: Harry 14 XYZ School
Static method:
 A static method is a general utility method that performs a task in isolation.
 A static method is bound to the class and not the object of the class.
Therefore, we can call it using the class name.
 A static method doesn’t have access to the class and instance variables
because it does not receive an implicit first argument like self and cls.
Therefore it cannot modify the state of the object or class.
 To make a method a static method, add @staticmethod decorator before
the method definition.
 The @staticmethod decorator is a built-in function decorator in Python to
declare a method as a static method.
 It is an expression that gets evaluated after our function is defined.
Static method:

Completed task_1
Completed task_2
Completed task_3
Completed task_1
destructor:

 Destructor is a special method that is called when an object gets


destroyed.
 Destructor is used to perform the clean-up activity before destroying
the object.
 Python has a garbage collector that handles memory management
automatically. For example, it cleans up the memory when an object
goes out of scope.
 But it’s not just memory that has to be freed when an object is
destroyed. We must release or close the other resources object were
using, such as open files, database connections, cleaning up the
buffer or cache.
destructor:

 Destructor gets called in the following two cases


 When an object goes out of scope.
 The reference counter of the object reaches 0.
 In Python, The special method __del__() is used to define a
destructor.
 when we execute del object_name destructor gets called
automatically and the object gets garbage collected.
destructor:
destructor:

 __del__() method is automatically called by Python when the instance


is about to be destroyed. It is also called a finalizer or (improperly) a
destructor.
 Syntax of destructor declaration:-
def __del__(self):
# body of a destructor
 def: The keyword is used to define a method.
 __del__() Method: It is a reserved method. This method gets called as
soon as all references to the object have been deleted
 self: The first argument self refers to the current object.
destructor:

Inside Constructor
Object initialized
Hello, my name is Emma
Inside destructor
Object destroyed
Encapsulation:
 Encapsulation in Python describes the concept of bundling data and
methods within a single unit.
 For example, when you create a class, it means you are implementing
encapsulation.
 A class is an example of encapsulation as it binds all the data
members (instance variables) and methods into a single unit.
Encapsulation:
 Using encapsulation, we can hide an object’s internal representation
from the outside. This is called information hiding.
 Encapsulation allows us to restrict accessing variables and methods
directly and prevent accidental data modification by creating private
data members and methods within a class.
 Encapsulation is a way to can restrict access to methods and
variables from outside of class.
 Whenever we are working with the class and dealing with sensitive
data, providing access to all variables used within the class is not a
good choice.
Access specifier:
 Access specifiers or access modifiers in python programming are used to
limit the access of class variables and class methods outside of class while
implementing the concepts of inheritance.
 This can be achieved by: Public, Private and Protected keyword.
 There are three types of access specifiers or access modifiers
 1). Public access modifier
 2). Private access modifier
 3). Protected access modifier
Access specifier:
Access specifier:
Access specifier:
 Public Access Modifier:-
 All the variables and methods (member functions) in python are by default
public.
 Any instance variable in a class followed by the ‘self’ keyword ie.
self.var_name are public accessed.
 Public data members are accessible within and outside of a class.
Access specifier:

Name: Jessa Salary: 10000


Name: Jessa Salary: 10000
Access specifier:
 Private Access Modifier:-
 Private members of a class (variables or methods) are those members which are
only accessible inside the class.
 We cannot use private members outside of class.
 To define a private variable add two underscores as a prefix at the start of a
variable name. ex: self.__varname
 It is also not possible to inherit the private members of any class (parent class) to
derived class (child class).
 Any instance variable in a class followed by self keyword and the variable name
starting with double underscore ie. self.__varName are the private accessed
member of a class.
Access specifier:

AttributeError: 'Employee' object has no attribute '__salary'


Access Private member outside of a class
using an instance method:

Name: Jessa Salary: 10000


Access specifier:

 Protected Access Modifier :-


 Protected variables or we can say protected members of a class
are restricted to be used only by the member functions and
class members of the same class. And also it can be accessed
or inherited by its derived class ( child class ).
 Protected members are accessible within the class and also
available to its sub-classes. To define a protected member,
prefix the member name with a single underscore _.
 Ex: _varname
Access specifier:

Employee name : Jessa


Working on project : NLP
Project: NLP
Access specifier:

Name: Jessa 14
Name: Jessa 16
Access specifier:
Advantages of Encapsulation
 Security: The main advantage of using encapsulation is the security of the
data. Encapsulation protects an object from unauthorized access. It allows
private and protected access levels to prevent accidental data modification.
 Data Hiding: The user would not be knowing what is going on behind the
scene. They would only be knowing that to modify a data member, call the
setter method. To read a data member, call the getter method. What these
setter and getter methods are doing is hidden from them.
 Simplicity: It simplifies the maintenance of the application by keeping
classes separated and preventing them from tightly coupling with each
other.
 Aesthetics: Bundling data and methods within a class makes code more
readable and maintainable
inheritance

 The process of inheriting the properties of the parent class into a


child class is called inheritance.
 The existing class is called a base class or parent class and the new
class is called a subclass or child class or derived class.
 The main purpose of inheritance is the reusability of code because we
can use the existing class to create a new class instead of creating it
from scratch.
 In inheritance, the child class acquires all the data members,
properties, and functions from the parent class.
 A child class can also provide its specific implementation to the
methods of the parent class.
inheritance
 Syntax :-
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
inheritance

Types Of Inheritance :-
 Single inheritance
 Multiple Inheritance
 Multilevel inheritance
 Hierarchical Inheritance
 Hybrid Inheritance
inheritance

Single Inheritance:-
 In single inheritance, a child class inherits from a single-parent class.
Here is one child class and one parent class.
inheritance

Inside Vehicle class


Inside Car class
inheritance

Addition value1 : 10
Addition value2 : 15
Added value : 25

multiplication value1 : 20
multiplication value2 : 30
Multiplied value : 600

subraction value1 : 50
subraction value2 : 30
Subracted value : 20
inheritance

Multiple Inheritance:-
 In multiple inheritance, one child class can inherit from multiple
parent classes. So here is one child class and multiple parent
classes.
inheritance

Inside Person class


Name: Jessa Age: 28
Inside Company class
Name: Google location: Atlanta
Inside Employee class
Salary: 12000 Skill: Machine
Learning
inheritance

Multilevel Inheritance:-
 In multilevel inheritance, a class inherits from a child class or
derived class.
 Suppose three classes A, B, C.
 A is the superclass,
 B is the child class of A,
 C is the child class of B.
inheritance

Inside Vehicle class


Inside Car class
Inside SportsCar class
inheritance

Hierarchical Inheritance:-
 In Hierarchical inheritance, more than one child class is derived from
a single parent class.
 In other words, we can say one parent class and multiple child
classes.
inheritance

This is Vehicle
Car name is: BMW
This is Vehicle
Truck name is: Ford
inheritance

Hybrid Inheritance:-
 When inheritance is consists of multiple types or a combination of
different inheritance is called hybrid inheritance.
inheritance

Inside Vehicle class


Inside Car class
Inside SportsCar class
inheritance
super() function:-
 When a class inherits all properties and behavior from the parent class is called
inheritance. In such a case, the inherited class is a subclass and the latter class is
the parent class.
 In child class, we can refer to parent class by using the super() function. The
super function returns a temporary object of the parent class that allows us to call
a parent class method inside a child class method.
 Benefits of using the super() function:-
 We are not required to remember or specify the parent class name to access its
methods.
 We can use the super() function in both single and multiple inheritances.
 The super() function support code reusability as there is no need to write the
entire function
inheritance

Jessa works at Google


inheritance

Dog has four legs.


Dog is a warm-blooded animal.
inheritance
Method Overriding
 In inheritance, all members available in the parent class are by default
available in the child class.
 If the child class does not satisfy with parent class implementation, then
the child class is allowed to redefine that method by extending additional
functions in the child class.
 This concept is called method overriding.
 When a child class method has the same name, same parameters, and
same return type as a method in its superclass, then the method in the
child is said to override the method in the parent class.
inheritance
Method Overriding
inheritance
Method Overriding

max speed is 200 Km/Hour


inheritance
Method Resolution Order:-
 In Python, Method Resolution Order(MRO) is the order by which Python
looks for a method or attribute.
 First, the method or attribute is searched within a class, and then it
follows the order we specified while inheriting.
 This order is also called the Linearization of a class, and a set of rules is
called MRO (Method Resolution Order).
 The MRO plays an essential role in multiple inheritances as a single
method may found in multiple parent classes.
inheritance
Method Resolution Order:-
 In multiple inheritance, the following search order is followed.
 First, it searches in the current parent class if not available, then searches
in the parents class specified while inheriting (that is left to right.)
 We can get the MRO of a class. For this purpose, we can use either the
mro attribute or the mro() method.
inheritance
In class C
[<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
In class B
[<class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
Polymorphism
 Polymorphism in Python is the ability of an object to take many
forms.
 Polymorphism allows us to perform the same action in many
different ways.
 In polymorphism, a method can process objects differently
depending on the class type or data type.
Polymorphism
Polymorphism
Polymorphism With Inheritance:-
 Polymorphism is mainly used with inheritance. In inheritance, child
class inherits the attributes and methods of a parent class.
 The existing class is called a base class or parent class, and the new
class is called a subclass or child class or derived class.
 Using method overriding polymorphism allows us to defines
methods in the child class that have the same name as the methods
in the parent class.
 This process of re-implementing the inherited method in the child
class is known as Method Overriding.
Polymorphism
Advantage of method overriding:-
 It is effective when we want to extend the functionality by altering
the inherited method. Or the method inherited from the parent class
doesn’t fulfill the need of a child class, so we need to re-implement
the same method in the child class in a different way.
 Method overriding is useful when a parent class has multiple child
classes, and one of that child class wants to redefine the method.
The other child classes can use the parent class method. Due to
this, we don’t need to modification the parent class code
 In polymorphism, Python first checks the object’s class type and
executes the appropriate method when we call the method.
Polymorphism
Polymorphism
Advantage of method overriding:-
 It is effective when we want to extend the functionality by altering
the inherited method. Or the method inherited from the parent class
doesn’t fulfill the need of a child class, so we need to re-implement
the same method in the child class in a different way.
 Method overriding is useful when a parent class has multiple child
classes, and one of that child class wants to redefine the method.
The other child classes can use the parent class method. Due to
this, we don’t need to modification the parent class code
 In polymorphism, Python first checks the object’s class type and
executes the appropriate method when we call the method.
Polymorphism

Details: Car x1 Red 20000


Car max speed is 240
Car change 7 gear
Details: Truck x1 white 75000
Vehicle max speed is 150
Vehicle change 6 gear
Polymorphism

Circle
I am a two-dimensional shape.
Squares have each angle equal
to 90 degrees.
153.93804002589985
Polymorphism
Polymorphism In Class methods:-
 Polymorphism with class methods is useful when we group different
objects having the same method.
 we can add them to a list or a tuple, and we don’t need to check the
object type before calling their methods.
 Instead, Python will check object type at runtime and call the correct
method.
 Thus, we can call the methods without being concerned about which
class type each object is. We assume that these methods exist in
each class.
Polymorphism

Petrol
Max speed 350
Diesel
Max speed is 240
Polymorphism
Polymorphism In Class methods:-
 As you can see, we have created two classes Ferrari and BMW. They
have the same instance method names fuel_type() and max_speed().
However, we have not linked both the classes nor have we used
inheritance.
 We packed two different objects into a tuple and iterate through it
using a car variable.
 It is possible due to polymorphism because we have added the same
method in both classes Python first checks the object’s class type
and executes the method present in its class.
Polymorphism
Polymorphism In Function and Object:-
 We can create polymorphism with a function that can take any
object as a parameter and execute its method without checking its
class type.
 Using this, we can call object actions using the same function
instead of repeating method calls.
Polymorphism

Petrol
Max speed 350
Diesel
Max speed is 240
Polymorphism
Polymorphism In Built-in Methods:-
 It means a method can process objects differently depending on the
class type or data type.
 The built-in function reversed(obj) returns the iterable by reversing
the given object.
 For example, if you pass a string to it, it will reverse it. But if you
pass a list of strings to it, it will return the iterable by reversing the
order of elements (it will not reverse the individual string).
Polymorphism
Polymorphism In In Built-in Methods:-

Reverse string
evitanYP
Reverse list
Kelly Jessa Emma
Polymorphism
Method Overloading:-
 The process of calling the same method with different parameters is
known as method overloading.
 Python does not support method overloading.
 Python considers only the latest defined method even if you overload
the method.
 Python will raise a TypeError if you overload the method.
Polymorphism
Method Overloading:-
Polymorphism
Method Overloading:-

Area of Square is: 25


Area of Rectangle is: 15
Polymorphism
Operator Overloading in Python:-
 Operator overloading means changing the default behavior of an
operator depending on the operands (values) that we use. In other
words, we can use the same operator for multiple purposes.
 For example, the + operator will perform an arithmetic addition
operation when used with numbers. Likewise, it will perform
concatenation when used with strings.
 The operator + is used to carry out different operations for distinct
data types. This is one of the most simple occurrences of
polymorphism in Python.
Polymorphism

300
JessRoy
[10, 20, 30, 'jessa', 'emma', 'kelly']
Polymorphism
Overloading + operator for custom objects:-
 Suppose we have two objects, and we want to add these two objects
with a binary + operator. However, it will throw an error if we
perform addition because the compiler doesn’t add two objects
Polymorphism
Overloading + operator for custom objects:-
 Python provides some special or magic function that is automatically
invoked when associated with that particular operator.
 For example, when we use the + operator, the magic method
__add__() is automatically invoked.
 Internally + operator is implemented by using __add__() method. We
have to override this method in our class if you want to add two
custom objects.
Polymorphism
Overloading + operator for custom objects:-

Total number of pages: 700


Polymorphism
Overloading * operator for custom objects:-

Worked for 50 days


salary is: 40000
abstraction
 The process by which data and functions are defined in such a way
that only essential details can be seen and unnecessary
implementations are hidden is called Data Abstraction.
 In Python, abstraction can be achieved by using abstract classes
and interfaces.
 A class that consists of one or more abstract method is called the
abstract class. Abstract methods do not contain their
implementation.
 Abstract class can be inherited by the subclass and abstract method
gets its definition in the subclass.
abstraction
 Abstraction classes are meant to be the blueprint of the other class.
An abstract class can be useful when we are designing large
functions.
 An abstract class is also helpful to provide the standard interface for
different implementations of components.
abstraction
Abstract Class:
 An Abstract class can contain the both method normal and abstract
method.
 An Abstract cannot be instantiated; we cannot create objects for the
abstract class.
 An object of the derived class is used to access the features of the
base class.
 The abstract class is an interface.
 Interfaces in OOP enable a class to inherit data and functions from a
base class by extending it.
abstraction
Abstract Class:
 Python provides the abc module to use the abstraction in the Python
program.
Syntax :-
from abc import ABC
class ClassName(ABC):
 We import the ABC class from the abc module.
abstraction
Abstract Base Classes:
 An abstract base class is the common application program of the
interface for a set of subclasses.
 It can be used by the third-party, which will provide the
implementations such as with plugins.
 It is also beneficial when we work with the large code-base hard to
remember all the classes.
abstraction
Working of the Abstract Classes:
 Unlike the other high-level language, Python doesn't provide the
abstract class itself.
 We need to import the abc module, which provides the base for
defining Abstract Base classes (ABC).
 The ABC works by decorating methods of the base class as abstract.
It registers concrete classes as the implementation of the abstract
base.
 We use the @abstractmethod decorator to define an abstract method
or if we don't provide the definition to the method, it automatically
becomes the abstract method.
abstraction

The mileage is 30kmph


The mileage is 25kmph
The mileage is 24kmph
abstraction

Triangle has 3 sides


I have 4 sides
Pentagon has 5 sides
abstraction
Working of the Abstract Classes:
 The methods where the implementation may vary for any other
subclass are defined as abstract methods and need to be given an
implementation in the subclass definition.
 There are methods that have the same implementation for all
subclasses as well. There are characteristics that exhibit the
properties of the abstract class and so, must be implemented in the
abstract class itself. Otherwise, it will lead to repetitive code in all
the inherited classes. These methods are called concrete methods.
abstraction
Working of the Abstract Classes:
 The methods where the implementation may vary for any other
subclass are defined as abstract methods and need to be given an
implementation in the subclass definition.
 There are methods that have the same implementation for all
subclasses as well. There are characteristics that exhibit the
properties of the abstract class and so, must be implemented in the
abstract class itself. Otherwise, it will lead to repetitive code in all
the inherited classes. These methods are called concrete methods.
abstraction

I am going to sleep in a while


I can meow
I can hiss
THANK
YOU

You might also like