0% found this document useful (0 votes)
87 views22 pages

Python Unit 4

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 22

R20 Python unit4

V.K.R, V.N.B & A.G.K COLLEGE OF ENGINEERING::GUDIVADA


(Approved by AICTE, New Delhi & Affiliated to JNTUK, Kakinada)
An ISO 9001:2015 Certified Institute
Gudivada , Krishna District, Andhra Pradesh - 521301

UNIT:4

FILE OPERATIONS:
 Files are named locations on disk to store related information. They are used to permanently store data in a non-
volatile memory (e.g. hard disk).
 Since Random Access Memory (RAM) is volatile (which loses its data when the computer is turned off), we
usefiles for future use of the data by permanently storing them.
 When we want to read from or write to a file, we need to open it first. When we are done, it needs to be closed so
that the resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order:
1. Open a file
2. Read or write (perform operation)
3. Close the file
Opening Files in Python
Python has a built-in open() function to open a file. This function returns a file object, also called a handle, as it is
used to read or modify the file accordingly.
F = open("myfile.txt")
We can specify the mode while opening a file. In mode, we specify whether we want to read r, write w or append a
to the file. The default is reading in text mode. In this mode, we get strings when reading from the file.
MODE DESCRIPTION
r
Opens a file for reading. (default)
w
Opens a file for writing. Creates a new file if it
does notexist or truncates the file if it exists.
x
Opens a file for exclusive creation. If the file
already exists,the operation fails.
a
Opens a file for appending at the end of the file
withouttruncating it. Creates a new file if it does
not exist.
b
Opens in binary mode.
+
Opens a file for updating (reading and writing)

F = open("myfile.txt",'r') # read a file


F = open("myfile.txt",'w') # write a file
F = open("myfile.txt",'a') # appends a file

Closing Files in Python


When we are done with performing operations on the file, we need to properly close the file. Closing a file will
free upthe resources that were tied with the file. It is done using the close() method available in Python.
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python unit4

F = open("test.txt", 'r')# perform file


operationsF.close()

READING CONFIG FILES IN PYTHON:


Assume we have the following file, located in the same folder as Python:
Demo.txt
WELCOME TO
CSE.WELCOME
TO ALL.
Good Luck!
To read a file in Python, we must open the file in reading r mode.
There are various methods available for this purpose. We can use the read(size) method to read in the size number of
data. If the size parameter is not specified, it reads and returns up to the end of the file.
Example-1:
F = open("Demo.txt",'r')
print(F.read(5))
F.close()
Output-1:
WELCO

Example-2:
F = open("Demo.txt",'r')
print(F.read()) F.close()
Output-2:
WELCOME TO
CSE. WELCOME
TO ALL.
Good Luck!

Example-3:
F = open("Demo.txt",'r')
print(F.readlines()) F.close()
Output-3:
['WELCOME TO CSE.\n', 'WELCOME TO ALL.\n', 'Good Luck!']
Here, readlines() method read all lines in the form of list.

WRITING LOG FILES IN PYTHON:


In order to write into a file in Python, we need to open it in write w, append a mode.
If we open the file in write mode, then new file created and writes data on it.
If file is already exits then all the data in that file will be erased and new content will be stored.
If we open the file in append mode, then that file content will not be erased and new content will be added at the
end.
Example:
F = open("Demo.txt",'w')
F.write("welcome to all")
F.close()
Output:
Here output will stored in a Demo.txt file with the content of welcome to all.
Example:
F = open("Demo.txt",'a')
F.write("welcome to all")
F.close()

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python unit4

Output:
Here output will added at the end of Demo.txt file.

UNDERSTANDIND READ FUNCTIONS IN PYTHON:


Python provides inbuilt functions for creating, writing and reading files. There are two types of
files that can be handled in python, normal text files and binary files (written in binary language,
0s and 1s).
Text files: In this type of file, Each line of text is terminated with a special character called EOL
(End of Line), which is the new line character (‘\n’) in python by default.
Binary files: In this type of file, there is no terminator for a line and the data is stored after
converting it into machine-understandable binary language.
Access mode
Access modes govern the type of operations possible in the opened file. It refers to how the file
will be used once it’s opened. These modes also define the location of the File Handle in the file.
File handle is like a cursor, which defines from where the data has to be read or written in the
file. Different access modes for reading a file are –
Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file. If
the file does not exists, raises I/O error. This is also the default mode in which file is opened.
Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned at the
beginning of the file. Raises I/O error if the file does not exists.
Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not
exist. The handle is positioned at the end of the file. The data being written will be inserted at the
end, after the existing data.
Opening a File
It is done using the open() function. No module is required to be imported for this function.
Syntax:
File_object = open(r"File_Name", "Access_Mode")
The file should exist in the same directory as the python program file else, full address of the file
should be written on place of filename.
Note: The r is placed before filename to prevent the characters in filename string to be treated as
special character. For example, if there is \temp in the file address, then \t is treated as the tab
character and error is raised of invalid address. The r makes the string raw, that is, it tells that the
string is without any special characters. The r can be ignored if the file is in same directory and
address is not being placed.
# Open function to open the file "MyFile1.txt"# (same directory) in read mode and
file1 = open("MyFile.txt", "r")
# store its reference in the variable file1# and "MyFile2.txt" in D:\Text in file2 file2 = open(r"D:\Text\MyFile2.txt", "r+")

Here, file1 is created as object for MyFile1 and file2 as object for MyFile2.
Closing a file

close() function closes the file and frees the memory space acquired by that file. It is used atthe time when the file is
no longer needed or if it is to be opened in a different file mode.
Syntax:
File_object.close()

# Opening and Closing a file "MyFile.txt"# for object name file1.


file1 =open("MyFile.txt", "r")
file1.close()
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python unit4

READING FUNCTIONS FROM FILES:


There are three ways to read data from a text file.read() : Returns the read bytes in form of a string. Reads n
bytes, if no n specified, reads the entire file

File_object.read([n])
readline() : Reads a line of the file and returns in form of a string.For specified n, reads at most n byte
However, does not reads more than one line, even if n exceeds the length of the line.
File_object.readline([n])
readlines() : Reads all the lines and return them as each line a string element in a list.
File_object.readlines()

Example:
# Program to show various ways to# read data from a file
# Creating a file
file1 =open("myfile.txt", "w")
L =["This is Delhi \n", "This is Paris \n", "This is London \n"]# Writing data to a file
file1.write("Hello \n")file1.writelines(L)
file1.close() # to change file access modesfile1 = open("myfile.txt", "r+") print("Output of Read function is ")
print(file1.read())
print()
# seek(n) takes the file handle to the nth# bite from the beginning.
file1.seek(0)
print("Output of Readline function is ")print(file1.readline())
print() file1.seek(0)
# To show difference between read and readlineprint("Output of Read(9) function is ") print(file1.read(9))
print() file1.seek(0)
print("Output of Readline(9) function is ")print(file1.readline(9))
print()

file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
Output:
Output of Read function isHello
This is Delhi This is Paris This is London

Output of Readline function isHello

Output of Read(9) function isHello


Th
Output of Readline(9) function isHello

Output of Readlines function is


['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
UNDERSTANDING WRITE FUNCTIONS IN PYTHON:
Steps for writing to text files
To write to a text file in Python, you follow these steps:
First, open the text file for writing (or appending) using the open() function.
Second, write to the text file using the write() or writelines() method.

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python unit4
Third, close the file using the close() method.
The following shows the basic syntax of the open() function:
f = open(path_to_file, mode)
The open() function accepts many parameters. But you’ll focus on the first two:
The path_to_file parameter specifies the path to the text file that you want to open for writing.
The mode parameter specifies the mode for which you want to open the text file. For writing to a text file, you
use one of the following modes:
Mode Description

'w' Open a text file for writing text

'a' Open a text file for appending text

The open() function returns a file object. And the file object has two useful methods for writing text to the file:
write() and writelines().
The write() method writes a string to a text file and the writelines() method write a list of strings to a file at on
In fact, the writelines() method accepts an iterable object, not just a list, so you can pass a tuple of strings,
a set of strings, etc., to the writelines() method.
To write a line to a text file, you need to manually add a new line character:
f.write('\n') f.writelines('\n')
Code language: JavaScript (javascript)
And it’s up to you to add the new line characters.
Writing text file examples
The following example shows how to use the write() function to write a list of texts to a text file:
lines = ['Readme', 'How to write text files in Python'] with open('readme.txt', 'w') as f:
for line in lines:
f.write(line)
f.write('\n')
Python File writelines() Method
❮ File Methods

Example
Open the file with "a" for appending, then add a list of texts to append to the file:

f = open("demofile3.txt", "a") f.writelines(["See you soon!", "Over and out."])

f.close()

#open and read the file after the appending: f = open("demofile3.txt", "r") print(f.read())

OUTPUT:
Hello! Welcome to demofile2.txt This file is for testing purposes.
Good Luck!See you soon!Over and out.

The writelines() method writes the items of a list to the file.


Where the texts will be inserted depends on the file mode and stream position.
"a": The texts will be inserted at the current file stream position, default at the end of the file
"w": The file will be emptied before the texts will be inserted at the current file stream position default 0.

Syntax: file.writelines(list)Example
The same example as above, but inserting line breaks for each list item:
f = open("demofile3.txt", "a")
f.writelines(["\nSee you soon!", "\nOver and out."])f.close()

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python unit4
#open and read the file after the appending:
f = open("demofile3.txt", "r")print(f.read())
OUTPUT:
Hello! Welcome to demofile2.txt This file is for testing purposes. Good Luck!
See you soon!
Over and out.
manipulating file pointer using seek:
Python file method seek() sets the file's current position at the offset. The whence argument is optional defaults
to 0, which means absolute file positioning, other values are 1 which means seek relative to the cu position and
2 means seek relative to the file's end.
There is no return value. Note that if the file is opened for appending using either 'a' or 'a+', any seek() operawill
be undone at the next write.

If the file is only opened for writing in append mode using 'a', this method is essentially a no-op, but it rem
useful for files opened in append mode with reading enabled (mode 'a+').
If the file is opened in text mode using 't', only offsets returned by tell() are legal. Use of other offsets ca
undefined behavior.
Note that not all file objects are seekable.
Syntax
Following is the syntax for seek() method −
fileObject.seek(offset[, whence])

EXAMPLE:
# Python program to demonstrate# seek() method
# Opening "GfG.txt" text filef = open("GfG.txt", "r")
# Second parameter is by default 0 # sets Reference point to twentieth# index position from the beginningf.seek(20)
# prints current positionprint(f.tell())
print(f.readline())f.close()
OUTPUT:
20
When you have to explain it, it’s bad.
Example 2: Seek() function with negative offset only works when file is opened in binary mode. Lesuppose the binary
file contains the following text.
b'Code is like humor. When you have to explain it, its bad.'
# Python code to demonstrate# use of seek() function

# Opening "GfG.txt" text file# in binary mode


f = open("data.txt", "rb")
# sets Reference point to tenth# position to the left from endf.seek(-10, 2)
# prints current positionprint(f.tell())
# Converting binary to string and# printing
print(f.readline().decode('utf-8'))
f.close()
Output:
47
, its bad.
PROGRAMMING ON FILE OPERATIONS IN PYTHON:
Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other
handling options, to operate on files. The concept of file handling has stretched over various other langua ges, but th
implementation is either complicated or lengthy, but alike other concepts of Python, this concept here is also easy a
short.
Working of open() function
We use open () function in Python to open a file in read or write mode. As explained above, open will return a file
object. To return a file object we use open() function along with two arguments, thaccepts file name and the mode,
whether to read or write. So, the syntax being: open(filename, mode). There are three kinds of mode, that Python
provides and how files can be opened:
“ r “, for reading.
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python unit4
“ w “, for writing.
“ a “, for appending.
“ r+ “, for both reading and writing
One must keep in mind that the mode argument is not mandatory. If not passed, then Python willassume it to be “ r ”
by default. Let’s look at this program and try to analyze how the read mode works:
# a file named "geek", will be opened with the reading mode. file=open('geek.txt', 'r')
# This will print every line one by one in the fileforeach infile:
print (each)

Working of read() mode


There is more than one way to read a file in Python. If you need to extract a string that contains allcharacters in the file
then we can use file.read(). The full code would work like this:
# Python code to illustrate read() modefile=open("file.text", "r")
print (file.read())
Another way to read a file is to call a certain number of characters like in the following code theinterpreter will read
the first five characters of stored data and return it as a string:
# Python code to illustrate read() mode character wisefile=open("file.txt", "r")
print (file.read(5))
Creating a file using write() mode
Let’s see how to create a file and how write mode works:
To manipulate the file, write the following in your Python environment:
# Python code to create a filefile = open('geek.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")file.close()
The close() command terminates all the resources in use and frees the system of this particularprogram.
Working of append() mode
Let’s see how the append mode works:
# Python code to illustrate append() modefile = open('geek.txt','a') file.write("This will add this line") file.close()
There are also various other commands in file handling that is used to handle various tasks like:
rstrip(): This function strips each line of a file off spaces from the right-hand sidlstrip(): This function strips
each line of a file off spaces from the left-hand side
It is designed to provide much cleaner syntax and exceptions handling when you are working withcode. That explains
why it’s good practice to use them with a statement where applicable. This is helpful because using this method any
files opened will be closed automatically after one is done,auto-cleanup.
Example:
# Python code to illustrate with()with open("file.txt") as file:
data = file.read()
# do something with data
Using write along with with() function
We can also use write function along with with() function:
# Python code to illustrate with() alongwith write()with open("file.txt", "w") as f:
f.write("Hello World!!!")
split() using file handling
We can also split lines using file handling in Python. This splits the variable when space isencountered. You can also
split using any characters as we wish. Here is the code:
# Python code to illustrate split() functionwith open("file.text", "r") as file:
data = file.readlines()forline indata:
word = line.split()print(word)
There are also various other functions that help to manipulate the files and its contents. One canexplore various other
functions in Python Docs.
OBJECT ORIENTED PROGRAMMING:
Python has been an object-oriented language since it existed. Because of this, creating and using classes and objects are
downright easy. However, here is small introduction of Object-Oriented Programming (OOP) tobring you at speed.
Overview of OOP Terminology
Class: A user-defined prototype for an object that defines a set of attributes that characterize any object ofthe class.
The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.
Instance/Object: An individual object of a certain class. An object obj that belongs to a class Circle, forexample, is
an instance of the class Circle.
Instantiation: The creation of an instance of a class.

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python unit4

Data member: A class variable or instance variable that holds data associated with a class and its objects.
Class variable: A variable that is shared by all instances of a class. Class variables are defined within a class but
outside any of the class's methods. Class variables are not used as frequently as instance variables are.
Instance variable: A variable that is defined inside a method and belongs only to the current instance of a class.
Function overloading: The assignment of more than one behaviour to a particular function. The operation performed
varies by the types of objects or arguments involved.
Inheritance: The transfer of the characteristics of a class to other classes that are derived from it.
Method: A special kind of function that is defined in a class definition.
Encapsulation: Using OOP in Python, we can restrict access to methods and variables. This prevents data fromdirect
modification which is called encapsulation. In Python, we denote private attributes using underscore as the prefix i.e
single _ or double.

CONCEPT OF CLASS:
A class is created with the keyword class and then writing the ClassName. The simplest form of class definition looks like
this:
Syntax:
class ClassName:
statement-1statement-2
.
.
<statement-N>
Class definitions, like function definitions (def statements) must be executed before they have any effect.
Example: class Student:
def _ _init_ _(self):
self.name="Mothi" self.branch="CSE" def display(self):
print("Name is",self.name) print("Branch is",self.branch)
Here, _ _init_ _ is a constructor and display is a method.
When we run the above program, it won’t give any output. Because, we didn’t use the class. To use this class we haveto
create and object and call the method.
To use this class we have to create and object and call the method.
OBJECTS AND INSTANCES:
To create an object, the following syntax is used:
objectName = ClassName( )
So, to create an object to Student class, we can write as:
s1 = Student()
To call the display method, we can write as:
s1.display()
When creating the object the following steps takes place internally:
First of all, a block of memory is allocated on heap. How much memory is to be allocated is decided from the
attributes and methods available in the Student class.
After allocating the memory block, the special method by the name ‘ init (self)’ is called internally. This method
stores the initial data into the variables. Since this method is useful to construct the instance, it is called
‘constructor’.
Finally, the allocated memory location address of the instance is returned into ‘s1’ variable.

Finally, the program looks like:


Example: class Student:
def _ _init_ _(self):

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python unit4

self.name="Mothi" self.branch="CSE" def display(self):


print("Name is",self.name) print("Branch is",self.branch)s1 = Student()
s1.display()
Output:
Name is MothiBranch is CSE

CONSTRUCTOR:
Constructors are generally used for instantiating an object. The task of constructors is to initialize (assign values) tothe
data members of the class when an object of class is created. In Python the init () method is called the constructor and
is always called when an object is created.
Syntax:
def init (self):
# body of the constructor
Types of constructors:
Default constructor: The default constructor is simple constructor which doesn’t accept any arguments. It isdefinition has
only one argument which is a reference to the instance being constructed.

Example: class Student:


def _ _init_ _(self):
self.name="Mothi" self.branch="CSE" def display(self):
print("Name is",self.name) print("Branch is",self.branch)s1 = Student()
s1.display()
Output:
Name is MothiBranch is CSE

Parameterized constructor: constructor with parameters is known as parameterized constructor. The parameterized
constructor take its first argument as a reference to the instance being constructed known as self and the rest of the
arguments are provided by the programmer.
Example: class Student: def _ _init_ _(self,n,b):self.name=n

self.branch=b
def display(self):
print("Name is",self.name) print("Branch is",self.branch)s1 = Student("Mothi","CSE") s1.display()
Output:
Name is MothiBranch is CSE
ATTRIBUTES AND DESTRUCTOR:
Python deletes unneeded objects (built-in types or class instances) automatically to free the memory space. The process
by which Python periodically reclaims blocks of memory that no longer are in use is termed as Garbage Collection.
Python's garbage collector runs during program execution and is triggered when an object's referencecount reaches zero.
An object's reference count changes as the number of aliases that point to it changes.
The del () method is a known as a destructor method in Python. It is called when all references to the object havebeen
deleted i.e when an object is garbage collected.
Syntax:
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.
Destructor:
Python deletes unneeded objects (built-in types or class instances) automatically to free the memory space. The process
by which Python periodically reclaims blocks of memory that no longer are in use is termed as Garbage Collection.
Python's garbage collector runs during program execution and is triggered when an object's referencecount reaches zero.
An object's reference count changes as the number of aliases that point to it changes.
The del () method is a known as a destructor method in Python. It is called when all references to the object havebeen
deleted i.e when an object is garbage collected.
Syntax:
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python unit4

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.

real time use of class in live projects:

Building WhatsApp bot on Python


A WhatsApp bot is application software that is able to carry on communication with humansin a spoken or written
manner. And today we are going to learn how we can create a
WhatsApp bot using python. First, let’s see the requirements for building the WhatsApp botusing python language.
How to make Flappy Bird Game in Pygame?
We all are familiar with this game. In this game, the main objective of the player is to gain themaximum points by
defending the bird from hurdles. Here, we will build our own Flappy Bird game using Python.
We will be using Pygame(a Python library) to create this Flappy Bird game. Pygame is anopen-source library that is
designed for making video games. it helps us to create fully functional games and multimedia programs in python.
First of all, You have to install the Pygame library using the command:-
pip install pygame
Share WhatsApp Web without Scanning QR code using Python:
Web-Whatsapp store sessions
Web Whatsapp stores sessions in IndexedDB with the name wawc and syncs those key- value pairs to local storage.
IndexedDB stores the data inside the user’s browser and allowsto create web application that can query from this
indexedDB with or without a network connection.
Python – Web App To Send Push Notification To Your Phone:
Pushbullet
Pushbullet, a prominent Python package, which connects multiple devices using python code. In this article, we will
discuss how to send messages or notifications through it. Using our computer and python code, we will send some
messages to the pushbullet app installed on a mobile device, which has the same login id, as the one on the computer.
For this first, we’ll need to create an account on Pushbullet.com and sign in to it, from computer and phoneboth.

Rock, Paper, Scissor game – Python Project


we will see how we can create a rock paper and scissor game using Tkinter. Rock paper scissor is a hand game usually
played between two people, in which each player simultaneously forms one of the three shapes with an outstretched
hand. These shapes are“rock”, “paper”, and “scissors”.
Game Winner Conditions
Let there be a Player who is playing with a computer as an opponent. Now,
If the player selects Paper and Computer Selects Scissor – Computer wins
If the player selects Rock and Computer Selects Scissor – Player 1 wins
If the player selects Paper and Computer Selects Rock – Player 1 wins
And If the player selects Paper and Computer Selects Paper – Draw
If the player selects Rock and Computer Selects Rock – Draw
If the player selects Scissor and Computer Selects Scissor – DrawTools and Technologies Used
Tkinter: It is a standard Python interface to the Tk GUI toolkit shipped with Python.Python with tkinter is the fastest
and easiest way to create the GUI applications.
Random: Python defines a set of functions that are used to generate or manipulaterandom numbers through the random
module.
PIL: Python Imaging Library (expansion of PIL) is the de facto image processing package
for Python language. It incorporates lightweight image processing tools that aids in editing,creating and saving images.

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python unit4

INHERITANCE:
Software development is a team effort. Several programmers will work as a team to develop software.
When a programmer develops a class, he will use its features by creating an instance to it. When another programmer
wants to create another class which is similar to the class already created, then he need not create theclass from the
scratch. He can simply use the features of the existing class in creating his own class.
Deriving new class from the super class is called inheritance.
The child class inherits the attributes of its parent class, and you can use those attributes as if they were defined inthe
child class.
A child class can also override data members and methods from the parent.
Syntax:
class Subclass(BaseClass):
<class body>
When an object is to SubClass is created, it contains a copy of BaseClass within it. This means there is a relation
between the BaseClass and SubClass objects.
We do not create BaseClass object,but still a copy of it is available to SubClass object.

The super( ) method:


super( ) is a built-in method which is useful to call the super class constructor or methods from the sub class.
Any constructor written in the super class is not available to the sub class if the sub class has a constructor. Then how
can we initialize the super class instance variables and use them in the sub class?
This is done by calling super class constructor using super( ) method from inside the sub class constructor.
super( ) is a built-in method which contains the history of super class methods.
Hence, we can use super( ) to refer to super class constructor and methods from a sub class. So, super( ) can be usedas:

super().init() # call super class constructor


super().init(arguments) # call super class constructor and pass argumentssuper().method() # call super class method
Example:
class Application_1:
def chat(self):
print("Message Chatting !")
class Application_2(Application_1):
def chat(self):
super().chat()
print("Emogies Chatting !")
a2=Application_2()a2.chat()
Output:
Message Chatting !
Emogies Chatting !
Here, chat() method from Application_1 class is called in Application_2.
Types of inheritance:
There are mainly 3 types of inheritance.
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Single inheritance

Deriving one or more sub classes from a single base class is called ‘single inheritance’. In single inheritance, we always
have only one base class, but there can be n number of sub classes derived from it. For example, ‘Application_1’ is a
single base class from where we derive ‘Application_2’as sub class. This is called single inheritance.

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python unit4

Example:
class Application_1:
def chat(self):
print("Message Chatting !")
class Application_2(Application_1):
def chat(self):
super().chat()
print("Emogies Chatting !")
a2=Application_2()a2.chat()
Output:
Message Chatting !
Emogies Chatting. !

Multiple inheritance
Deriving sub classes from multiple (or more than one) base classes is called ‘multiple Inheritance’. All the members of
super classes are by default available to sub classes and the sub classes in turn can have their own members.
The best example for multiple inheritance is that parents are producing the children and the children inheriting the
qualities of the parents.

Example:
class Application_1:
def chat(self):
print("Message Chatting !")
class Application_2:
def chat(self):
print("Emogies Chatting !")
class Application_3(Application_1,Application_2):
def chat(self):
super().chat()
print("Images/Videos Chatting !")
a3=Application_3()a3.chat()
Output:
Message Chatting !
Images/Videos Chatting !
Here, only Application_1 chat() method will be executed, Application_2 chat() method will not be executed. In multiple
inheritance if two super classes will have same method name then only first super class methodwill be executed.
Problem in Multiple inheritance:
If the sub class has a constructor, it overrides the super class constructor and hence the super class constructor isnot
available to the sub class.
But writing constructor is very common to initialize the instance variables.
In multiple inheritance, let’s assume that a sub class ‘C’ is derived from two super classes ‘A’ and ‘B’ having their
own constructors. Even the sub class ‘C’ also has its constructor.
Multilevel Inheritance

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python unit4

Deriving one sub classes from a single base class and deriving another sub class one sub class is called ‘Multilevel
inheritance’.

!
Method Overloading:
Python does not support method overloading by default. But there are different ways to achieve method overloading in
Python. The problem with method overloading in Python is that we may overload the methods but can only use the latest
defined method.
To overcome the problem we can use the following method.

Overloading Operators:
Python operators work for built-in classes. But the same operator behaves differently with different types. For example, the +
operator will perform arithmetic addition on two numbers, merge two lists, or concatenate two strings.This feature in Python
that allows the same operator to have different meaning according to the context is called operator overloading.
So what happens when we use them with objects of a user-defined class? Let us consider the following class, whichtries to
simulate a point in 2-D coordinate system.
Example:
class Demo:
def init (self, x=0, y=0):
self.x = xself.y = y
d1 = Demo(1, 2)d2 = Demo(2, 3)print(d1+d2) Output:
Traceback (most recent call last):
File "C:/Python36-32/OPER_overload.py", line 7, in <module>print(d1+d2)
TypeError: unsupported operand type(s) for +: 'Demo' and 'Demo'
It shows an error, because we are performing addition operation on objects.
In Python, there is a special functions with double underscore _ _.Suppose we want the print() function to print thecoordinates
of the Demo object instead of what we got. We can define a str () method in our class that controls how the object gets printed.
Let's look at how we can achieve this:
Example:
class Demo:
def init (self, x=0, y=0):
self.x = xself.y = y
def str (self):
return "{0} {1}".format(self.x, self.y)d1 = Demo(1, 2)
print(d1)
d2 = Demo(2, 3)print(d2) Output:
12
23
Overloading + operator:
To overload the + operator, we will need to implement add () function in the class. With great power comes great
responsibility. We can do whatever we like, inside this function. But it is more sensible to return a Demo object of the
coordinate sum.

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python unit4

Similarly, we can Expression Internally


overload other operators
as well. The special
function that we need to
implement is tabulated
below. Operator
Addition p1 + p2 p1._ _add_ _(p2)
Subtraction p1 - p2 p1._ _sub_ _(p2)
Multiplication p1 * p2 p1._ _mul_ _(p2)
Power p1 ** p2 p1._ _pow_ _(p2)
Division p1 / p2 p1._ _truediv_
_(p2)
Floor Division p1 // p2 p1._ _floordiv_
_(p2)
Remainder (modulo) p1 % p2 p1._ _mod_ _(p2)
Bitwise Left Shift p1 << p2 p1._ _lshift_
_(p2)
Bitwise Right p1 >> p2 p1._ _rshift_
Shift _(p2)
Bitwise AND p1 & p2 p1._ _and_ _(p2)
Bitwise OR p1 | p2 p1._ _or_ _(p2)
Bitwise XOR p1 ^ p2 p1._ _xor_ _(p2)
Bitwise NOT ~p1 p1._ _invert_ _()
Less than p1 < p2 p1._ _lt_ _(p2)
Less than or equal p1 <= p2 p1._ _le_ _(p2)
to
Equal to p1 == p2 p1._ _eq_ _(p2)
Not equal to p1 != p2 p1._ _ne_ _(p2)
Greater than p1 > p2 p1._ _gt_ _(p2)
Greater than or p1 >= p2 p1._ _ge_ _(p2)
equal to
Less than p1 < p2 p1._ _lt_ _(p2)
Less than or equal p1 <= p2 p1._ _le_ _(p2)
to
Equal to p1 == p2 p1._ _eq_ _(p2)
Not equal to p1 != p2 p1._ _ne_ _(p2)
Greater than p1 > p2 p1._ _gt_ _(p2)

ADDING AND RETRIEVING OF DYNAMIC ATTRIBUTES OF CLASS:


Dynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects
or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance
attribute for nearly anything in Python.
Example:
class Demo:pass d1=Demo()
d1.a=45
print("first object a=",d1.a)d2=Demo()
d2.a=54
print("second object a=",d2.a)
Output:
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python unit4

first object a= 45 second object a= 54


PROGRAMMING USING OOPS SUPPORT:
OOP in Python
Python is a great programming language that supports OOP. You will use it to define
a class with attributes and methods, which you will then call.
Python offers a number of benefits compared to other programming languages like
Java, C++ or R. It's a dynamic language, with high-level data types. This means that
development happens much faster than with Java or C++. It does not require the
programmer to declare types of variables and arguments. This also makes Python
easier to understand and learn for beginners, its code being more readable and
intuitive.
How to create a class
To define a class in Python, you can use the classkeyword, followed by theclass name and a colon. Inside the class,
an init method has to be defined with def. This is the initializer that you can later use to instantiate
objects. It's similar to a constructor in Java. init must always be present! It takes one argument: self,
which refers to the object itself. Inside the method, the pass keyword is used as of now, because Python expects
you to type something there. Remember to use correct indentation!

class Dog:

def init (self):


pass

Note: selfin Python is equivalent to thisin C++ or Java.

In this case, you have a (mostly empty) Dogclass, but no object yet. Let'screate one!

Instantiating objects
To instantiate an object, type the class name, followed by two brackets. Youcan assign this to a variable to keep
track of the object.
ozzy = Dog()

And print it:


print(ozzy)

< main .Dog object at 0x111f47278>

Adding attributes to a class


After printing ozzy, it is clear that this object is a dog. But you haven't addedany attributes yet. Let's give the Dog
class a name and age, by rewriting it:
class Dog:
def init (self, name, age):

self.name = name
self.age = age

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python unit4

To access an object's attributes in Python, you can use the dot notation. This is done by typing the name of the
object, followed by a dot and the attribute'sname.

print(ozzy.name)
print(ozzy.age)
Ozzy

The str() function is used here to convert


the age attribute, which is an integer, to a string,so you can use it in the print() function.
print(ozzy.name + " is " + str(ozzy.age) + " year(s) old.") Ozzy is 2 year(s) old.

Define methods in a class


Now that you have aDogclass, it does have a name and age which you cankeep track of, but it doesn't actually do
anything. This is where instance methods come in. You can rewrite the class to now include
a bark()method. Notice how the defkeyword is used again, as well asthe selfargument.
class Dog:

def init (self, name, age):


self.name = name
self.age = age
def bark(self):
print("bark bark!")

The bark method can now be called using the dot notation, after instantiating a new ozzy object. The
method should print "bark bark!" to the screen.
Notice the parentheses (curly brackets) in .bark(). These are always used when calling a
method. They're empty in this case, since the bark()methoddoes not take any arguments.
ozzy = Dog("Ozzy", 2)
ozzy.bark() bark bark!

DESIGN WITH CLASSES:


Python Classes and Objects:
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of
bundling data and functionality together. Creating a new class creates a new type of object, allowing new
instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state.
Class instances can also have methods (defined by their class) for modifying their state.
To understand the need for creating a class let’s consider an example, let’s sayyou wanted to track the number of
dogs that may have different attributes like breed, age. If a list is used, the first element could be the dog’s breed
while thesecond element could represent its age. Let’s suppose there are 100 different dogs, then how would you
know which element is supposed to be which? What if you wanted to add other properties to these dogs? This
lacks organization and it’s the exact need for classes.Class creates a user-defined data structure, which holds its
own data membersand member functions, which can be accessed and used by creating an instance of that class. A
class is like a blueprint for an object.
Some points on Python class:
Classes are created by keyword class.Attributes are the variables that belong to a class.
Attributes are always public and can be accessed using the dot (.) operator.Eg.: Myclass.Myattribute

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python unit4

Class Definition Syntax:


class ClassName: # Statement-1
.
.
.
# Statement-N
Defining a class –
# Python3 program to
# demonstrate defining# a class

class Dog:
pass

CLASS OBJECTS: An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of
the class with actual values. It’s not an idea anymore, it’s an actual dog, like a dog of breed pug who’s seven
years old. You can have many dogs to create many different instances, but without the class as a guide, you
would be lost, not knowing what information is required.
An object consists of :
State: It is represented by the attributes of an object. It also reflects theproperties of an object.
Behavior: It is represented by the methods of an object. It also reflects theresponse of an object to other objects.
Identity: It gives a unique name to an object and enables one object tointeract with other objects.

Declaring Objects (Also called instantiating a class)


When an object of a class is created, the class is said to be instantiated. All theinstances share the attributes and
the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class
may have any number of instances.
Example:

Python3 program to
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python unit4

# demonstrate instantiating# a class


class Dog:
# A simple class# attribute attr1 = "mammal"attr2 ="dog"
# A sample methoddeffun(self):
print("I'm a", self.attr1)print("I'm a", self.attr2)
# Driver code
# Object instantiationRodger =Dog()

# Accessing class attributes# and method through objectsprint(Rodger.attr1) Rodger.fun()

Output:
mammal
I'm a mammalI'm a dog
In the above example, an object is created which is basically a dog named Rodger. This class only has two class
attributes that tell us that Rodger is a dogand a mammal.
The self
Class methods must have an extra first parameter in the method definition. We do not give a value for this
parameter when we call the method, Python provides it.
If we have a method that takes no arguments, then we still have to have one argument.
This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as myobject.method(arg1, arg2), this is automatically converted by Python
into MyClass.method(myobject, arg1, arg2)
– this is all the special self is about.
__init__ method
The __init__ method is similar to constructors in C++ and Java. Constructorsare used to initializing the object’s
state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at
the time of Object creation. It runs as soon as an object of a class is instantiated.The method is useful to do any
initialization you want to do with your object.

 Python3

# A Sample class with init methodclassPerson:


# init method or constructordef init (self, name):
self.name = name
# Sample Method def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Nikhil')p.say_hi()

Output:
Hello, my name is Nikhil

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python unit4

Class and Instance Variables


Instance variables are for data, unique to each instance and class variables are for attributes and methods shared
by all instances of the class. Instance variables are variables whose value is assigned inside a constructor or
method with self whereas class variables are variables whose value is assigned in the class.
Defining instance variable using a constructor.

 Python3
# Python3 program to show that the variables with a value
# assigned in the class declaration, are class variables and# variables inside methods and constructors are instance
# variables.
# Class for DogclassDog:
# Class Variableanimal ='dog'
# The init method or constructordef init (self, breed, color):
# Instance Variableself.breed = breed self.color = color
# Objects of Dog class Rodger = Dog("Pug", "brown")
Buzo = Dog("Bulldog", "black")
print('Rodger details:') print('Rodger is a', Rodger.animal)print('Breed: ', Rodger.breed) print('Color: ', Rodger.color)
print('\nBuzo details:') print('Buzo is a', Buzo.animal)print('Breed: ', Buzo.breed) print('Color: ', Buzo.color)
# Class variables can be accessed using class# name also
print("\nAccessing class variable using class name")print(Dog.animal)

Output:
Rodger details:Rodger is a dogBreed: Pug Color: brown
Buzo details:
Buzo is a dog
Breed: BulldogColor: black
Accessing class variable using class nameDog

DATA MODELLING EXAMPLES:


A datastore entity has a key and a set of properties. An application uses the datastore API to define datamodels, and create
instances of those models to be stored as entities. Models provide a common structure to the entities created by the API, and
can define rules for validating property values.
Data model class
The example below may be a little silly, but it gets the point across. Since the code is an
example, we are skipping a lot of other variables that the class would store.
In real code, size might be an enum.
# data.py
class Data(object):
_number_of_slices = int()
_size = str() # real code might use an enum
_price_in_cents = int()
# real code would define a lot more class variables
def set_number_of_slices(self, num): self._number_of_slices = num
def get_number_of_slices(self):return self._number_of_slices
def set_size(self, size):self._size = size
def get_size(self):
return self.size
. Example
Creating a class that can store and expose data makes writing code easier. It makes your code clean and clear to the
reader. In the example below, the program prompts for the size of the pizza, stores that size, and then retrievesthe
size to confirm.
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python unit4

# main.py

from data import Data

d = Data() # create an instance of the Data class

print('What size pizza would you like? ') # prompts = input() # wait for input
d.set_size(s) # store input in data model
print(f'To confirm, you asked for a {d.get_size} pizza')
Add extra value to the data model
Our pizza program could be enhanced to get user input for a large number ofvariables. At the end of the prompting
section, we want to display all of the choices the user made back to them so they can visually confirm their order.
We can take advantage of the string built-in class method.
data.py
class Data(object):
_number_of_slices = int()
...
def _str_(self):
print(f'Size: {self.get_size()}')
print(f'Slices: {self.get_number_of_slices()}') print(f'Toppings: {self._get_toppings()}')
Case Study on ATM:
Program:
class ATM:
def init (self):self.balance=0.0
def check_balance(self): print("Balance is",self.balance)def deposit(self):
amount=float(input("Enter amount to deposit: "))if amount<=0:
print("Deposite amount should be greater than Zero")else:
self.balance+=amount print("Amount Deposited")def withdraw(self):
amount=float(input("Enter amount to withdraw: "))if amount<=0:
print("Withdraw amount should be grater than Zero")elif amount>self.balance:
print("Amount could not be withdrawn")else:
self.balance-=amount print("Amount Withdrawn")a1=ATM()
while True:
print("1.Balance Check 2.Deposit 3.Withdraw 4.Exit")ch=int(input("Enter Your Choice: "))
if ch==1: a1.check_balance()elif ch==2:
a1.deposit() elif ch==3: a1.withdraw()elif ch==4:
breakelse:
print("Invalid Choice")
Output:
1.Balance Check 2.Deposit 3.Withdraw 4.Exit Enter Your Choice: 1
Balance is 0.0
1.Balance Check 2.Deposit 3.Withdraw 4.ExitEnter Your Choice: 2
Enter amount to deposit: 500
Amount Deposited
1.Balance Check 2.Deposit 3.Withdraw 4.ExitEnter Your Choice: 1
Balance is 500.0
1.Balance Check 2.Deposit 3.Withdraw 4.ExitEnter Your Choice: 2
Enter amount to deposit: 500Amount Deposited
1.Balance Check 2.Deposit 3.Withdraw 4.ExitEnter Your Choice: 1
Balance is 1000.0
1.Balance Check 2.Deposit 3.Withdraw 4.Exit Enter Your Choice: 3
Enter amount to withdraw: 400Amount Withdrawn

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python unit4

1.Balance Check 2.Deposit 3.Withdraw 4.Exit Enter Your Choice: 1


Balance is 600.0
1.Balance Check 2.Deposit 3.Withdraw 4.Exit
Enter Your Choice: 4
STRUCTURING CLASSES WITH INHERITANCE AND POLYMORPHISM:
Inheritance and polymorphism – this is a very important concept in Python. You mustunderstand it
better if you want to learn.
Inheritance
One of the major advantages of Object Oriented Programming is re-use. Inheritance is one of the
mechanisms to achieve the same. Inheritance allows programmer to create a general or a base class first
and then later extend it to more specialized class. It allows programmer to write better code.
Using inheritance you can use or inherit all the data fields and methods available in your base class. Later
you can add you own methods and data fields, thus inheritance provides a way to organize code, rather
than rewriting it from scratch.
In object-oriented terminology when class X extend class Y, then Y is called super/parent/base class and
X is called subclass/child/derived class. One point to note here is that only data fields and method which
are not private are accessible by child classes. Private data fields and methods are accessible only inside
the class.
syntax to create a derived class is −
class BaseClass:
Body of base class
class DerivedClass(BaseClass):Body of derived class
Inheriting Attributes
Now look at the below example −

Output

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python unit4

Polymorphism (“MANY SHAPES”)


Polymorphism is an important feature of class definition in Python that is utilized when you have
commonly named methods across classes or subclasses. This permits functions to use entities of different
types at different times. So, it provides flexibility and loose coupling so that code can be extended and
easily maintained over time.
This allows functions to use objects of any of these polymorphic classes without needing to be aware of
distinctions across the classes.
Polymorphism can be carried out through inheritance, with subclasses making use of base class methods
or overriding them.
Let understand the concept of polymorphism with our previous inheritance example and add one common
method called show_affection in both subclasses −
From the example we can see, it refers to a design in which object of dissimilar type can be treated in the
same manner or more specifically two or more classes with method of the same name or common
interface because same method(show_affection in below example) is called with either type of objects.

Output:

VKR,VNB&AGK COLLEGE OF ENGINEERING

You might also like