Python Unit4 (Original)
Python Unit4 (Original)
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.
# 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()
We can call this parameter by any name, other than class BCA:
self if we want. name = 'Python'
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:
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.
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:
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.