0% found this document useful (0 votes)
10 views

Python Unit4 (Original)

Uploaded by

vikasmanjunath58
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Python Unit4 (Original)

Uploaded by

vikasmanjunath58
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

PYTHON

PROGRAMMING
(Course code: 21BCA3C10L)

BY
Pankaja Benkal
Asst. Professor
Dept of computer science
NCMS
PYTHON UNIT -IV
File Handling:
 File Types;
 Operations on Files– Create, Open, Read, Write, Close Files;
 File Names and Paths;
 Format Operator
Object Oriented Programming:
 Classes and Objects;
 Creating Classes and Objects;
 Constructor Method;
 Classes with Multiple Objects;
 Objects as Arguments;
 Objects as Return Values;
 Inheritance-
 Single and Multiple Inheritance,
 Multilevel and Multipath Inheritance;
 Encapsulation- Definition, Private Instance Variables;
 Polymorphism- Definition, Operator Overloading
File Handling in Python
File handling is the process of saving data in a Python program in the form of outputs or inputs, The python file can be
store in the form of binary file or a text file. There are six different types of modes are available in Python programming
language.
1. r – read an existing file by opening it.
2. w – initiate a write operation by opening an existing file. If the file already has some data in it, it will be
overwritten; if it doesn’t exist, it will be created.
3. a – Open a current file to do an add operation. Existing data won’t be replaced by it.
4. r+ – Read and write data to and from the file. It will replace any prior data in the file.
5. w+ – To write and read data, use w+. It will replace current data.
6. a+ – Read and add data to and from the file. Existing data won’t be replaced by it.
What is the need for File Handling?
In computer science, we have programs for performing all sorts of tasks. A program may require to read data from the
disk and store results on the disk for future usage. This is why we need file handling. For instance, if you need to
analyse, process and store data from a website, then you first need to scrap(this means getting all the data shown on a
web page like text and images) the data and store it on your disk and then load this data and do the analysis and then
store the processed data on the disk in a file.
Types of Files BINARY FILE
The data files are the files that store data pretaning to a specific What is Binary File?
application, for later use. • A binary file contains arbitrary binary data i.e. numbers stored
Python allow us to create and manage three types of file in the file, can be used for numerical operation(s).
1. TEXT FILE • So when we work on binary file, we have to interpret the raw
bit pattern(s) read from the file into correct type of data in
2. BINARY FILE our program.
3. CSV (Comma separated values) files • In the case of binary file it is extremely important that we
interpret the correct data type while reading the file.
TEXT FILE
• Python provides special module(s) for encoding and decoding
What is Text File? of data for binary file.
• A text file is usually considered as sequence of lines.
• Line is a sequence of characters (ASCII or UNICODE), stored on
permanent storage media.
• The default character coding in python is ASCII each line is
terminated by a special character, known as End of Line (EOL).
• At the lowest level, text file will be collection of bytes.
• Text files are stored in human readable form and they can also
be created using any text editor.
CSV files Operations on Files–
What is CSV File?  Create
• A comma-separated values (CSV) file is a  Open
delimited text file that uses a comma to separate values.  Read
• Each line of the file is a data record.  Write
• Each record consists of one or more fields, separated by  Close Files
commas.
Opening and Closing a File in Python
• The use of the comma as a field separator is the source of the
open() Function:
name for this file format.
This function takes two arguments. First is the
• CSV file is used to transfer data from one application to
filename along with its complete path, and the other
another. is access mode. This function returns a file object.
• CSV file stores data, both numbers and text in a plain text. Syntax:

open(filename, mode)
Important points:
The file and python script should be in the same directory.
Else, you need to provide the full path of the file.
By default, the access mode is read mode if you don't Opens the file for appending. If the file is
9. a present, then the pointer is at the end of
specify any mode. the file, else it creates a new file for writing.
Access mode tells the type of operations possible in the
opened file. There are various modes in which we can
open a file. Let's see them: 10. ab
Same as a mode, except this opens the file
in binary format.
No. Modes Description
Opens a file in read-only mode. The pointer of the file is at the
1. r Opens the file for appending and reading.
beginning of the file. This is also the default mode.
The file pointer is at the end of the file if
11. a+
2. rb Same as r mode, except this opens the file in binary mode. the file exists, else it creates a new file for
reading and writing.
Opens the file for reading and writing. The pointer is at the
3. r+
beginning of the file.
4. rb+ Same as r+ mode, except this, opens the file in binary mode.
Same as a+ mode, except this, opens the
Opens the file for writing. Overwrites the existing file and if the 12. ab+
5. w file in binary format.
file is not present, then creates a new one.

6. wb Same as w mode, except this opens the file in binary format.


Opens the file for both reading and writing, rest is the same
7. w+
as w mode.
8. wb+ Same as w+ except this opens the file in binary format.
Example of Opening and Closing Files in Python close() function:
Code: This function doesn't take any argument, and you can
directly call the close() function using the file object.
# When the file is in the same folder where the python
script is present. Also access mode is 'r' which is read It can be called multiple times, but if any operation is
mode. performed on the closed file, a "ValueError"
exception is raised.
file = open('test.txt',mode='r')
Syntax:

# When the file is not in the same folder where the python file.**close()**
script is present. In this case, the whole path of the file
should be written.
You can use the 'with' statement with open also, as it
file = open('D:/data/test.txt',mode='r') provides better exception handling and simplifies it
by providing some cleanup tasks.

It is general practice to close an opened file as a closed file Also, it will automatically close the file, and you don't
reduces the risk of being unwarrantedly updated or read. have to do it manually.
We can close files in python using the close function.
Let's discuss it.
Example using with statement
Code:
with open("test.txt", mode='r') as f:
# perform file operations
The method shown in the above section is not entirely safe.
If some exception occurs while opening the file, then the
code will exit without closing the file. A safer way is to use a
try-finally block while opening files.
Code:
try:
file = open('test.txt',mode='r')
# Perform file handling operations
finally:
file.close()

Now, this guarantees that the file will close even if an


exception occurs while opening the file.
So, you can use the ‘with’ statement method instead. Any of
the two methods is good.
Python – Create New File A new file will be created in the present working
directory. You can also provide a complete path to the
To create a new file with Python, use open() method with file if you would like your file to be created at an
“x” as second parameter and the filename as first absolute path in the computer.
parameter.
Example 2: Create a New File with the same name as
that of existing file
myfile = open("complete_filepath", "x")
In the following example, we will try creating a new
file sample.txt. But this file is already present in the
same location.
The open() method with options shown in the above code
snippet creates an empty file Python Program
Example 1: Create a New File using open() f = open("sample.txt", "x")
In the following example, we will create a new file named f.close
sample.txt. You will get FileExistsError with a similar stack trace as
Python Program below.
#open file Output
f = open("sample.txt", "x") Traceback (most recent call last):
#close file File “sample.py", line 1, in <module>
f.close f = open("sample.txt", "x")
FileExistsError: [Errno 17] File exists: 'sample.txt'
Read Text File in Python Output
To read text file in Python, follow these steps.
 Call open() builtin function with filepath and mode 2. Read only few characters from the text file
passed as arguments. open() function returns a file
If you need to read only specific number of
object.
characters, say N number of characters, present at the
 Call read() method on the file object. read() returns a starting of the file, pass N (number) as argument to
string. read() function.
 The returned string is the complete text from the text In the following Python program, we will read first 20
file. characters in the file.
Examples
1. Read a text file “sample.txt” Python Program
In the following Python program, we will open sample.txt f = open("sample.txt", "r")
file in read mode. We will read all the contents of the text
file and print the text to the console. data = f.read(20)
print(data)
Python Program Output
fileObject = open("sample.txt", "r") Welcome to pythonexa
data = fileObject.read() read(20) function returned the first 20 characters
from the text file.
print(data)
3. Read the file in text mode Closing a File
read, write and execute modes are based on the The close() function is used to close a file.
permissions. There are text and binary based on the
nature of content.
In the following example, we will open the file in text Syntax of the Python close function:
mode explicitly by providing “t” along with the read “r”
mode. File_object.close()
Python Program
f = open("sample.txt", "rt") Example:
data = f.read() j=open(“simple.txt”,”r”)
print(data) k=j.read()
print(k)
Output j.close()
Welcome to pythonexamples.org Output:
Hello Nagarjuna
File Names and Paths
To understand path we must be familiar with the terms:
DRIVE, FOLDER/DIRECTORY, FILES.
Our hard disk is logically divided into many parts called
Drives like C drive, D drive etc.

The drive is the main container in which we put


everything to store.
The naming format is DRIVE_LETTER:
For Ex C: , D:
 Drive is also known as ROOT DIRECTORY.
 Drive contains Folders and files
 Folder contains sub-folders or files.
 Files are the actual data container.
ABSOLUTE PATH: • ggg
Absolute path is the full address of any file or folder
From the drive i.e. from root folder . It is like
Drive_name:\Folder\Folder…..\filename
For eg absolute path of file Python_unit4.ppt will be
C:\Users\panka\OneDrive\Documents\NCMS\
NEP_notes\Python_unit4.ppt
RELATIVE PATH:
Relative path is the location of file/folder from the current
folder.
To use relative path special symbols are:
Single dot(.):it refers to current folder
Double dot(..): it refers to parent folder.
Backslash(\):first backslash before(.) and double
dot(..)refers to the ROOT folder.
Getting name of current working directory
Import os
pwd=os.getcwd()
Print(“current directory :”,pwd)
Format operator
The file format operator is a way to format strings for output to a file. The operator uses the syntax % symbol followed
by one or more format codes and optionally a format specifier.
For example
name=“Robert”
age=50
#writing to a file using format operator
with open (“simple.txt”,”w”) as file:
file write(“name:%s\n age:%d” %name(name,age))
In the above example , the %s is a format code for a string and the %d is a format code for an integer. The values
for name and age are passed in the parenthesis after the format codes.
Python Object-Oriented Programming • As you may notice, the data (attributes) are always
nouns, while the behaviors (method) are always
(OOP) verbs.
What Is Object-Oriented • This compartmentalization is the central concept of
Programming in Python? Object-Oriented Programming. You build objects
 Object-Oriented Programming (OOP) is a programming that store data and contain specific kinds of
prototype in which we can think about complex functionality.
problems as objects. Why Do We Use Object-Oriented
 A prototype is a theory that supplies the base for Programming in Python?
solving problems. OOP allows you to create secure and reliable
 So when we’re talking about OOP, we’re referring to a software. Many Python frameworks and libraries use
set of concepts and patterns we use to solve problems this prototype to build their codebase. Some
with objects. examples are pandas, NumPy, etc.
 An object in Python is a single collection of data
(attributes) and behavior (methods). You can think of
objects as real things around you. For example,
consider calculators:
The main advantages of using OOP in Python. Class and Objects in Python
 All Modern Programming Languages Use OOP  Suppose you wish to store the number of books
you have, you can simply do that by using a
This paradigm is language-independent. If you learn OOP
variable. Or, say you want to calculate the sum of 5
in Python, you’ll be able to use it in the following:
numbers and store it in a variable, well, that can be
Java, PHP, JavaScript done too!
 OOP Allows You to Code Faster  Primitive data structures like numbers, strings, and
lists are designed to store simple values in a
Coding faster doesn’t mean writing fewer lines of code. It variable. Suppose, your name, or square of a
means you can implement more features in less time number, or count of some marbles (say).
without compromising the stability of a project.
 But what if you need to store the details of all the
Object-Oriented programming allows you to reuse code by Employees in your company?
implementing abstraction. This principle makes your code
more concise and legible.  For example, you may try to store every employee
 OOP Helps You Avoid Spaghetti Code in a list, you may later be confused about which
index of the list represents what details of the
OOP gives us the possibility of compressing all the logic in employee(e.g. which is the name field, or the
objects, therefore avoiding long pieces of nested if’s. empID etc.)
 OOP Improves Your Analysis of Any Situation
Once you get some experience with OOP, you’ll be able to
think of problems as small and specific objects.
Example: IMPORTANT:
employee1 = ['John ', 104120, "Developer", "Dept. 2A"] A class just defines the structure of how anything
employee2 = ['Mark', 211240, "Database Designer", "Dept. 11B"]
should look. It does not point to anything or anyone in
particular.
employee3 = [‘Smith ', 131124, "Manager", "Dept. 2A"]
For example, say, HUMAN is a class, which has
Even if you try to store them in a dictionary, after an suppose -- name, age, gender, city. It does not point to
extent, the whole codebase will be too complex to handle. any specific HUMAN out there, but yes, it explains the
So, in these scenarios, we use Classes in python. properties and functions any HUMAN should or any
A class is used to create user-defined data structures in object of class HUMAN should have.
Python. An instance of a class is called the object. It is the
Classes define functions, which are termed methods, that implementation of the class and exists in real.
describe the behaviors and actions that an object created
from a class can perform.
An object is a collection of data (variables) and
Classes make the code more manageable by avoiding methods (functions) that access the data. It is the real
complex codebases. It does so, by creating a blueprint. implementation of a class.
It defines what properties or functions, any object which
is derived from the class should have.
Example:
• However, "Ron" is an object of the Human class
(please refer to the image given above for
understanding).
• That means, Ron is created by using the
blueprint of the Human class, and it contains the
real data.
• "Ron" exists physically, unlike "Human" (which
just exists logically).
• He exists in real, and implements all the
properties of the class Human, such as, Ron have
a name, he is 15 years old, he is a male, and lives
in Delhi.
• Also, Ron implements all the methods of Human
class, suppose, Ron can walk, speak, eat, and
sleep.
Consider this example, here Human is a class - It is just a • And many humans can be created using the
blueprint that defines how Human should be, and not a real blueprint of class Human. Such as, we may
implementation. create 1000s of more humans by referring to the
blueprint of the class Human, using objects.
You may say that "Human" class just exists logically.
Note: • In the next indented lines(statement 1..n) are the
members of the class. Also, the variables inside the
class = blueprint(suppose an architectural drawing). The class are known as attributes. The attributes can be
Object is an actual thing that is built based on the accessed later on in the program using the dot(.)
‘blueprint’ (suppose a house). operator.
An instance is a virtual copy (but not a real copy) of the • The syntax for creating a Class in Python is as
object. follows:
When a class is defined, only the blueprint of the object is class ClassName:
created, and no memory is allocated to the class. # Statement 1
Memory allocation occurs only when the object or # Statement 2
instance is created. .
The object or instance contains real data or information. .
# Statement n
Creating a Class in Python
• Creating a class is as easy as creating a function in example of a class named python.
Python. In function, we start with the def keyword class python:
while class definitions begin with the keyword class.
pass
• Following the keyword class, we have the class
identifier(i.e. the name of the class we created) and Note: The keyword pass denotes an empty class. It is
then the : (colon) operator after the class name. written just to avoid any errors in the console while
running the above code.
What is Object in Python? The object is created using the name of the class.
Classes are user-defined blueprints that help us create an The syntax of creating an object of a particular class is
“object”. as follows:
Objects are the instances of a particular class.
[object_name] = [class_name](arguments/parameters)
Every other element in Python will be an object of some
class, such as the string, dictionary, number(10,40), etc.
will be an object of some corresponding built-in class(int,
str) in Python. Accessing Object's variables in Python
# Creating a class named Scaler
class number:
a = 10
b = 25
c = 50
# Creating an object named "obj1", "obj2" & accessing
Creating an object in Python the class properties(attributes).
After declaring a class in Python, when we create an obj1 = number()
instance of that class, it is known as the object of the
class. print(obj1.a)
The process of creating an object is called instantiation. print(obj1.b)
Python Class Attributes # Accessing the values of the attributes
These are the variables that are defined inside the print(BCA.Course1)
particular class and can be used by all the objects. These print(BCA.Course3)
attributes can, later on, be called by using the class and
attribute name with the dot(.) operator. # Accessing through object instantiation.
example: obj= BCA()
class BCA: print(obj.Course2)
Course = 'Python’ Output:
• Here we have a class named BCA, with a class attribute Python
named Course with a fixed value (ie ‘Python’). Java
• Note: The value of any attributes will remain the same
C++
for all objects until and unless it is changed explicitly
later on in the code.  Here we have defined several attributes inside the
BCA Class.
example to define some attributes and access it.
 Also, we have shown two ways of accessing the
class BCA: values of those attributes.
Course1 = 'Python'  One, by directly using the class name and the other
Course2 = 'C++' by using an object(class instance).
Course3 = 'Java'  Assigning a class to a variable is known as object
instantiation.
Note: If we change the value of the attribute using the print(BCA. Course) # Value haven't changed
class name(the first method in the above example), then it
obj2= BCA()
would change across all the instances of that class.
print(obj2. Course) # Value haven't changed
While if we change the value of an attribute using class
instance(object instantiation), it would only change the Output:
value of the attribute in that instance only.
class BCA: Machine Learning
Course = 'Python' AI
# Changing value using Class Name Using class instance would not reflect the
BCA.Course = 'Machine Learning' changes to other instances
obj = BCA() Machine Learning
print(obj. Course)
Machine Learning
# Changing value using Class Instance
obj. Course = 'AI'
print(obj. Course) # Value will change in this instance only
print('Using class instance would not reflect the changes
to other instances')
Python Class Methods Let’s take a look at an example of the same.
Once we have defined the class attributes, we can even class BCA:
define some functions inside the particular class that can
access the class attribute and can add more functionality def CourseDetails(self):
to the existing code. print('Course Information')
These defined functions inside a class are known as We can also pass other arguments inside the
methods. We can define as many methods as we want
CourseDetails function if we want.
inside a single class.
Syntax:
For example, let’s say we have a class BCA, in which
we have an attribute named “name” and a method
We define a method(function) inside a class using the named CourseDetails.
def keyword, followed by the method name. We then
pass some arguments through the method. The method would take the argument name along
with self.
Note: When we define a method, it must at least pass
a single parameter which is generally named as self. It We can also pass multiple arguments as per our
refers to the current instance of the class. requirements in the code.

We can call this parameter by any name, other than class BCA:
self if we want. name = 'Python'

def CourseDetails(self, name):


self.name = name
Constructor method in Python Rules of Python Constructor
What is a Constructor?  It starts with the def keyword, like all other
 A constructor is a unique function that gets called functions in Python.
automatically when an object is created of a class.  It is followed by the word init, which is prefixed
 The main purpose of a constructor is to initialize or and suffixed with double underscores with a pair
assign values to the data members of that class. of brackets, i.e., __init__().
 It cannot return any value other than none.  It takes an argument called self, assigning values
Syntax of Python Constructor: to the variables.
 It accepts the self-keyword as a first argument
def __init__(self):
which allows accessing the attributes or method
# initializations
of the class.
 Self is a reference to the current instance of the
init is one of the reserved functions in Python. In Object class.
Oriented Programming, it is known as a constructor.
 It is created and passed automatically/implicitly
to the __init__() when the constructor is called.
class Person: Types of Constructors in Python
def __init__(self, name, age):  Parameterized Constructor
self.name = name  Non-Parameterized Constructor
self.age = age
 Default Constructor

person = Person("John", 30)


print(person.name) 1. Parameterized Constructors
print(person.age)  Parameterized constructors are useful when you
Output want
John to create an object with custom values for its
attributes.
30
 They allow you to specify the values of the object’s
• In this example, the __init__ method is called when attributes when the object is created, rather than
the Person object is created, and it sets using
the name and age attributes of the object. default values.
• The __init__ method is commonly referred to as the
“constructor” because it is responsible for
constructing the object. It is called automatically
when the object is created, and it is used to initialize
the object’s attributes.
Here is an example of a class with a parameterized 2. Non-Parameterized Constructor in Python
constructor: When the constructor doesn't accept any arguments from the
class Person: object and has only one argument, self, in the constructor, it is
def __init__(self, name, age): known as a non-parameterized constructor.
self.name = name
This can be used to re-assign a value inside the constructor.
self.age = age
example:
class Fruits:
person = Person("Alice", 25)
favourite = "Apple"
print(person.name)
# non-parameterized constructor
print(person.age)
def __init__(self):
Output: self.favourite = "Orange"
Alice # a method
25 def show(self):
In this example, the __init__ method is the parameterized print(self.favourite)
constructor
# creating an object of the class
for the Person class.
obj = Fruits()
It takes two arguments, name and age, and it sets the values of
the # calling the instance method using the object obj
name and age attributes of the object to the values of these obj.show()
arguments.
Output: 3. Default Constructor in Python
Orange When you do not write the constructor in the class
created, Python itself creates a constructor during the
Explanation: compilation of the program.
 In the above example, we initialize our favorite fruit as
It generates an empty constructor that has no code in
Apple inside the class. it.
 But we want to change it as soon as the object gets Example
created.
class Assignments:
 This can be done by re-assigning the value to the
constructor. check= "not done"
 This type of constructor doesn't take any other # a method
argument other than self. def is_done(self):
 It can be used to print and check whether our value got
print(self.check)
changed.

# creating an object of the class


obj = Assignments()

# calling the instance method using the object obj

obj.is_done()
Output 2. The first argument of the constructor method
must be self.
not done
3. This is a reference to the object itself, and it is
Explanation
used to access the object’s attributes and
 In the above example, we check whether our methods.
assignment is done.
4. The constructor method must be defined inside
 We create an object of a class where we do not write the class definition. It cannot be defined outside
the constructor. the class.
 Python generates a constructor when we do not 5. The constructor method is called automatically
provide any to initialize the instance variables. It does when an object is created. You don’t need to call it
nothing. explicitly.
Rules of Python Constructor 6. You can define both default and parameterized
constructors in a class.
Here are some rules for defining constructors in Python:
7. If you define both, the parameterized constructor
will be used when you pass arguments to the
1. The constructor method must be named __init__. This object constructor, and the default constructor will
is a special name that is recognized by Python as the be used when you don’t pass any arguments.
constructor method.
Create Multiple Objects of Python Class Deleting an Object in Python
We can also create multiple objects from a single class. You created an object earlier and now want to
For example,
delete it? We also have a way to delete an object
# define a class
which was created earlier in the code by using
class Employee:
the del keyword.
# define an attribute
employee_id = 0 del obj1

# create two objects of the Employee class Note: After deleting the object of a class, the name
employee1 = Employee() of the object which is bound to it gets deleted, but
employee2 = Employee() however the object continues to exist in the
memory
# access attributes using employee1 with no name assigned to it. Later it is automatically
employee1.employeeID = 1001 destroyed by a process known as garbage collection.
print(f"Employee ID: {employee1.employeeID}")
Seminar Topic:

# access attributes using employee2


Objects as Arguments;
employee2.employeeID = 1002
Objects as Return Values
print(f"Employee ID: {employee2.employeeID}")
Inheritance in Python Example 1: Python Inheritance

Inheritance is the ability to ‘inherit’ features or attributes class Animal:


from already written classes into newer classes we make. # attribute and method of the parent class
OR name = ""
In Python inheritance, new class/es inherits from older def eat(self):
class/es. The new class/es copies all the older class's print("I can eat")
functions and attributes without rewriting the syntax in # inherit from Animal
the new class/es. These new classes are called derived
classes, and old ones are called base classes. class Dog(Animal):

Python Inheritance Syntax # new method in subclass


def display(self):
# define a superclass
# access name attribute of superclass using self
class super_class:
print("My name is ", self.name)
# attributes and method definition
# create an object of the subclass
# inheritance labrador = Dog()
class sub_class(super_class): # access superclass attribute and method
# attributes and method of super_class labrador.name = “Sheru"
# attributes and method of sub_class labrador.eat()
Here, we are inheriting the sub_class(derived) class from # call subclass method
the super_class(base) class. labrador.display()
In the above example, we have derived a subclass Dog
from a superclass Animal. Notice the statements,
labrador.name = "Rohu"
labrador.eat()
Here, we are using Labrador (object of Dog) to access
name and eat() of the Animal class. This is possible
because the subclass inherits all attributes and methods
of the superclass. Example
Also, we have accessed the name attribute inside the # python 3 syntax # single inheritance example
class parent: # parent class
method of the Dog class using self.
Types of Inheritance in Python def func1(self):

Single Inheritance in Python: print("Hello Parent")

Single Inheritance is the simplest form of inheritance class child(parent): # child class
where a single child class is derived from a single parent def func2(self): # we include the parent class
class. Due to its candid nature, it is also known as Simple print("Hello Child") # as an argument in the
Inheritance. child class
# Driver Code
test = child() # object created
test.func1() # parent method called via child
object
test.func2() # child method called
Multiple Inheritance in Python
Example:
In multiple inheritance, a single child class is inherited
from two or more parent classes. It means the child class Basic implementation of multiple inheritance
has access to all the parent classes' methods and
attributes.

However, if two parents have the same “named”


methods, the child class performs the method of the first
parent in order of reference. To better understand which
class’s methods shall be executed first, we can use the
Method Resolution Order function (mro). It tells the order
in which the child class is interpreted to visit the other
classes.

Note: To better understand which class’s methods shall be executed


first, we can use the Method Resolution Order function (mro). It tells
the order in which the child class is interpreted to visit the
Multilevel Inheritance in Python Example
In multilevel inheritance, we go beyond just a parent-child
relation. We introduce grandchildren, great
-grandchildren, grandparents, etc. We have seen only two
levels of inheritance with a superior parent class/es and a
derived class/es, but here we can have multiple levels
where the parent class/es itself is derived from another
class/es.
Hierarchical Inheritance in Python Example:
Hierarchical Inheritance is the right opposite of multiple
inheritance. It means that there are multiple derived
child
classes from a single-parent class.
Encapsulation in Python Example for Encapsulation
Encapsulation means binding data and variables inside a
class.

What is Encapsulation?
Encapsulation is the process of bundling data members
and methods inside a single class.
Bundling similar data elements inside a class also helps in
data hiding.  The major idea behind this mechanism is simple.
Encapsulation also ensures that objects of a class can  Suppose you have a variable that is not used on the
function independently.
outside of an object.
 It can be bundled with methods that provide read
or write access.
 Encapsulation allows you to hide certain
information and control access to the object’s
internal state.
Advantages of Encapsulation in Python Implementing Encapsulation in Python
Following are the advantages of Encapsulation in Python: Problem Statement:
• Protects an object from unauthorized access Add a new feature in the HR Management System
that shows an employee’s salary and the project they
• Prevents other classes from using the private members
are working on.
defined within the class
• Prevents accidental data modification by using private
and protected access levels For this, we will create a class Employee and add
some attributes like name, ID, salary, project, etc.
• Helps to enhance security by keeping the code/logic
safe from external inheritance. As per the requirement, let’s add two required
features (methods) – show_sal() to print the salary
• Bundling data and methods within a class makes code
and proj() to print the project working on
more readable and maintainable
Example: • Now let’s use Encapsulation to hide an object’s internal
representation from the outside and make things secure.
Whenever we work in a team and deal with sensitive data,
it’s not ideal to provide access to all variables used within
the class.
• So, we have talked a lot about securing using
Encapsulation, but how? This is where access modifiers
come into the picture.
Access Modifiers in Python
• Encapsulation is achieved by declaring a class’s data
members and methods as either private or protected.
• But in Python, we do not have keywords like public,
private, and protected, as in the case of Java. Instead, we
achieve this by using single and double underscores.
• Access modifiers are used to limit access to the variables
and methods of a class. Python provides three types of
access modifiers public, private, and protected.
• Public Member: Accessible anywhere from outside the
class.

Output: • Private Member: Accessible within the class.


Name: James Salary:100000 • Protected Member: Accessible within the class and its
sub-classes.
James is Working on Python
Public Member: Private Member
Public Members can be accessed from outside and within • We can protect variables in the class by marking them
the class. Making it easy to access by all. private.
By default, all the member variables of the class are • To make any variable a private just add two underscores
public. as a prefix at the start of its name. For example, __salary.
• Private members are accessible only within the class and
cannot be accessed from the objects of the class.

Output:
Name: James Salary:100000
NOTE: The output of the above code will throw an error, Example:
since we are trying to access a private variable that is
hidden from the outside.
How to access private methods outside the class?
Add private members inside a public method You can
declare a public method inside the class which uses a
private member and call the public method containing a
private member outside the class.
Polymorphism in Python Polymorphism in Python Example
Polymorphism, a fundamental concept in object- Let’s try to understand polymorphism and its
oriented programming, is the ability of one function to implementation even better through this simple example –
perform multiple functionalities. It can be implemented
in different ways, including operator overloading, built-
in functions, classes, and inheritance.
In operator overloading, the same operator is used in
The above code snippet is the simplest example. Over here,
Different ways, such as addition and string concatenation. the “+” operator is being overloaded.
What is Polymorphism in Python?
 The literal meaning of Polymorphism is - having Operator overloading is the concept of using an operator
different forms. beyond its pre-defined purpose.
 In programming, Polymorphism refers to a function So in our example, the “+” operator is performing addition
in the first line while the second line is an example of string
having the same name but being used in different ways
concatenation.
and different scenarios.
 This makes programming easier and more natural. The output would make the difference clear
Here, you can see how the same operator was used in two
different ways. Hence, operator overloading can be said to
be an implementation of Polymorphism in Python.
266
ScalerAcademy
Function of Polymorphism in Python Class Polymorphism in Python
In Python, there are several functions that depict Polymorphism in Python can also be implemented through
polymorphism by being compatible with multiple data classes. Python allows classes to have different methods
types. The best example of this is the in-built len() having the same name.
function.

Output
14
3
2
Now in this example, we have created two classes “Cat” Output
and “Cow”. They’re different animals and make different
sounds.
So, the make_sound() function should produce two
different outputs based on the objects we pass through Meow
them.
I am a cat. My name is Kitty. I am 2.5 years old.
In this case, we have created two objects “cat1” and
“cow1”. Meow
Moo
I am a Cow. My name is Fluffy. I am 4 years old.
Moo
Overloading Output:
Overloading is divided into two types Traceback (most recent call last):
 Operator Overloading File “G:\python pycharm project\main.py”, line 7, in
 Method Overloading <module>
total_fare=bus+ car
Operator overloading
TypeError: unsupported operand type(s) for +: ‘Vehicle’
Operator overloading is the type of overloading in
and ‘Vehicle’
which an operator can be used in multiple ways beyond
its predefined meaning. Here in the above example an error has occurred, this is
because python has no idea how to add two objects
>>>print(2*7)
together. Here Vehicle is the class.
14
let's create a class and try to use the + operator to add two
>>>print(”a”*3) objects of that class,
aaa
Now comes the application of operator overloading Let’s take an example for better understanding
here.
Now we will overload the special function __add__
operator.

Output

None None
Now if I want to pass any other value then I have to call
output another function obj.show() with an argument in it.
50
Method Overloading
Method overloading means a class containing multiple
methods with the same name but may have different
arguments. Basically python does not support method
overloading, but there are several ways to achieve
method overloading. Though method overloading can
be achieved, the last defined methods can only be
usable.
Now if we pass two argument during the function call
see what will happen in the next example,
Q:Find out all the operator
overloading functions and methods

Thank You
• Here as we pass two arguments 4 and 5 during
function call two different values are assigned for a
and b.
• So in the above example we have seen how we can
use the same method and use different function calls
in different ways.

You might also like