0% found this document useful (0 votes)
2 views10 pages

Python File Handling & OOP Concepts

The document covers file handling and object-oriented programming (OOP) concepts in Python. It explains file types, operations, and methods for reading and writing files, as well as OOP principles such as classes, objects, encapsulation, inheritance, and polymorphism. Additionally, it provides examples of constructors and operator overloading in Python.

Uploaded by

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

Python File Handling & OOP Concepts

The document covers file handling and object-oriented programming (OOP) concepts in Python. It explains file types, operations, and methods for reading and writing files, as well as OOP principles such as classes, objects, encapsulation, inheritance, and polymorphism. Additionally, it provides examples of constructors and operator overloading in Python.

Uploaded by

vivek87228
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT-IV – File Handling , Object-Oriented-Programming

What Does File Mean?


A file is a container in a computer system for storing information. A
file is a named location used for storing data. Files used in computers
are similar in features to that of paper documents used in library and office
files.

File Types: There are different types of files such as text files,
binary files, data files, directory files, and graphic files, and these different
types of files store different types of information. In a computer operating
system, files can be stored on optical drives, hard drives or other types of
storage devices.

Operations on Files :

1. Opening files using open() method


2. Reading files using read() method
3. Writing files using write() method
4. Closing files using close() method

Python File Open


Before performing any operation on the file like reading or writing, first, we have to
open that file. For this, we should use Python’s inbuilt function open() but at the time of
opening, we have to specify the mode, which represents the purpose of the opening
file.
f = open(filename, mode)
Where the following mode is supported:
1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already contains some data,
then it will be overridden but if the file is not present then it creates the file as well.
3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. This mode does not override the existing
data, but you can modify the data starting from the beginning of the file.
5. w+: To write and read data. It overwrites the previous file if one exists, it will
truncate the file to zero length or create a file if it does not exist.
6. a+: To append and read data from the file. It won’t override existing data.

Working in Read mode


There is more than one way to How to read from a file in Python . Let us see how we
can read the content of a file in read mode.
Example 1: The open command will open the Python file in the read mode and the for
loop will print each line present in the file.
Python
# a file named "geek", will be opened with the reading mode.
file = open('[Link]', 'r')

# This will print every line one by one in the file


for each in file:
print (each)

Output:
Helloworld
GeeksforGeeks
123 456

The following python program demonstrates the open, read, write,


close operations on files using open() with ‘w’,’r’,a’,’w+’,’a+’,’r+’ modes,
read(), readline(),readlines() write, writeline(), writelines(), seek() and
close () methods
file1 = open("[Link]","w")

L=["This is Delhi \n","This is Paris \n","This is Londan \n"]

[Link]("Hello \n")
[Link](L)
[Link]()

file1=open("[Link]","r+")
print("Output of Read Function is")
print([Link]())

[Link](0)
print("Output of Readline Function is")
print([Link]())

[Link](0)
print("Output of Read(9) Function is")
print([Link](9))

[Link](0)
print("Output of Readline(9) Function is")
print([Link](9))

[Link](0)
print("Output of Readlines Function is")
print([Link]())
[Link]()
------------------------------------------OUT PUT--------------------------------------
Output of Read Function is
Hello
This is Delhi
This is Paris
This is Londan

Output of Readline Function is


Hello

Output of Read(9) Function is


Hello
Th
Output of Readline(9) Function is
Hello

Output of Readlines Function is


['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is Londan \n']
OOPS concepts : Pillars of Objetct-Oriented-Programming Concepts are –
What is Object-Oriented Programming in Python?
Object-Oriented Programming (OOPs) is a programming paradigm that uses objects and
classes in programming. It aims to implement real-world entities like inheritance,
polymorphisms, encapsulation, etc. in the programming.

The main concept of object-oriented Programming (OOPs) or oops concepts in Python is to


bind the data and the functions that work together as a single unit so that no other part of the
code can access this data.

Class
The class can be defined as a collection of objects. It is a logical entity that has some specific
attributes and methods. For example: if you have an employee class, then it should contain an
attribute and method, i.e. an email id, name, age, salary, etc.

In Python, a class can be created by using the keyword class, followed by the class name. The
syntax to create a class is given below.

Syntax

class ClassName:
#statement_suite

Object
The object is a real world entity that has state/ Data and behavior/Methods. It
may be any real-world object like the mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods.
When we define a class, it needs to create an object to allocate the memory. Consider the
following example.

Example:

class car:
def __init__(self,modelname, year):
[Link] = modelname
[Link] = year
def display(self):
print([Link],[Link])

c1 = car("Toyota", 2016)
[Link]()
Output:
Toyota 2016

Encapsulation – It is a mechanism of wrapping up both data and methods in


a single entity.

Encapsulation is also an essential aspect of object-oriented programming. It is used to restrict


access to methods and variables. In encapsulation, code and data are wrapped together within a
single unit from being modified by accident.
Data Abstraction- Abstraction is a technique to hide internal details and show only
functionalities.

Data abstraction and encapsulation both are often used as synonyms. Both are nearly synonyms
because data abstraction is achieved through encapsulation.

Python Inheritance-It is mechanism used to derive new class called derived/child


class by acquiring the properties/traits of an existing class called base/parent class.
Inheritance is also called as REUSABILITY
Types of Inheritance : Single, Multiple, Multilevel,

Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code


reusability to the program because we can use an existing class to create a new class instead of
creating it from scratch.

In inheritance, the child class acquires the properties and can access all the data members and
functions defined in the parent class. A child class can also provide its specific implementation
to the functions of the parent class. In this section of the tutorial, we will discuss inheritance in
detail.

vIn python, a derived class can inherit base class by just mentioning the base in the bracket
after the derived class name. Consider the following syntax to inherit a base class into the
derived class.

Single Inheritance

Syntax
class derived-class(base class):
<class-suite>

A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the
following syntax.

Syntax
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>

Example 1
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
[Link]()
1. [Link]()

Output:

dog barking
Animal Speaking
Python Multi-Level inheritance

Multi-Level inheritance is possible in python like other object-oriented languages. Multi-level


inheritance is archived when a derived class inherits another derived class. There is no limit on
the number of levels up to which, the multi-level inheritance is archived in python.

The syntax of multi-level inheritance is given below.

Syntax
class class1:
<class-suite>

class class2(class1):
<class suite>

class class3(class2):
<class suite>

Example
class Animal:
def speak(self):
print("Animal Speaking")

#The child class Dog inherits the base class Animal


class Dog(Animal):
def bark(self):
print("dog barking")

#The child class Dogchild inherits another child class Dog


class DogChild(Dog):
def eat(self):
print("Eating bread...")

d = DogChild()
[Link]()
[Link]()
[Link]()

Output:

dog barking
Animal Speaking
Eating bread...
Python Multi-MULTIPLE inheritance

Python provides us the flexibility to inherit multiple base classes in the child class.

Syntax
class Base1:
<class-suite>

class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>

class Derived(Base1, Base2, ...... BaseN):


<class-suite>

Example
class Calculation1:
def Summation(self,a,b):
return a+b;

class Calculation2:
def Multiplication(self,a,b):
return a*b;

class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;

d = Derived()
print([Link](10,20))
print([Link](10,20))
print([Link](10,20))

Output:

30
200
0.5
Polymorphism :
Polymorphism refers to having multiple forms. POLY stands for MANY, MORPH is FORMS.
Polymorphism is a programming term that refers to the use of the same function name, but
with different signatures, for multiple types.

polymorphisms refer to the occurrence of something in multiple forms.

Example of in-built polymorphic functions:

# Python program for demonstrating the in-built poly-morphic functions

# len() function is used for a string


print ( len("Javatpoint") )

# len() function is used for a list


print ( len( [110, 210, 130, 321] ) )

Output:

10
4

Operator Overloading in Python

Operator Overloading means giving extended meaning beyond their predefined


operational meaning. For example operator + is used to add two integers as well as join two
strings and merge two lists. It is achievable because ‘+’ operator is overloaded by int class and
str class. You might have noticed that the same built-in operator or function shows different
behavior for objects of different classes, this is called Operator Overloading.

# Python program to show use of


# + operator for different purposes.

print(1 + 2)

# concatenate two strings


print("Geeks"+"For")

# Product two numbers


print(3 * 4)

# Repeat the String


print("Geeks"*4)

Output
3
GeeksFor
12
GeeksGeeksGeeksGeeks
Constructors in Python :- The task of constructors is to initialize(assign values) to the
data members of the class when an object of the class is created. In Python the __init__()
method is called the constructor and is always called when an object is created.

Syntax of constructor declaration :


def __init__(self):
# body of the constructor

Types of constructors :
 default constructor: The default constructor is a simple constructor which doesn’t accept
any arguments. Its definition has only one argument which is a reference to the instance
being constructed.
 parameterized constructor: constructor with parameters is known as parameterized
constructor. The parameterized constructor takes 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 of default constructor :

class CMSforCMS:

# default constructor
def __init__(self):
[Link] = "CMSforCMS"

# a method for printing data members


def print_Geek(self):
print([Link])

# creating object of the class


obj = CMSforCMS()

# calling the instance method using the object obj


obj.print_Geek()

Output
CMSforCMS

Example of the parameterized constructor :


class Addition:
first = 0
second = 0
answer = 0

# parameterized constructor
def __init__(self, f, s):
[Link] = f
[Link] = s

defdisplay(self):
print("First number = " + str([Link]))
print("Second number = " + str([Link]))
print("Addition of two numbers = " +
str([Link]))

def calculate(self):
[Link] = [Link] + [Link]

# creating object of the class


# this will invoke parameterized constructor
obj1 = Addition(1000, 2000)

# creating second object of same class


obj2 = Addition(10, 20)

# perform Addition on obj1


[Link]()

# perform Addition on obj2


[Link]()

# display result of obj1


[Link]()

# display result of obj2


[Link]()

Output
First number = 1000
Second number = 2000
Addition of two numbers = 3000
First number = 10
Second number = 20
Addition of two numbers = 30

You might also like