Python Exp No. 9 and 10
Python Exp No. 9 and 10
123
Experiment No. 9
Programs to understand Object oriented Programming
(OOP) concepts: classes, objects and methods
Aim: To study classes, objects and methods
Theory:
Features of OOP
Programmers are able to produce faster, more accurate and better- written
applications
The four major principles of object orientation are: Encapsulation, Data Abstraction
, Inheritance , Polymorphism
Procedural programming also focuses on the idea that all algorithms are executed
with functions and data that the programmer has access to and is able to change.
Object-Oriented programming is much more similar to the way the real world
works; it is analogous to the human brain. Each program is made up of many
entities called objects.
Instead, a message must be sent requesting the data, just like people must ask one
another for information; we cannot see inside each other’s heads.
What is an Object..?
124
Objects are the basic run-time entities in an object-oriented system.
They may represent a person, a place, a bank account, a table of data or any item that
the program must handle.
When a program is executed the objects interact by sending messages to one another.
Driver
OnDuty ,
NumPassengers
Location
PickUp
DropOff
GoOnDuty
GoOffDuty
GetNumPassengers
What is a Class?
A class is a special data type which defines how to build a certain kind of object.
The class also stores some data items that are shared by all the instances of this
class
Instances are objects that are created which follow the definition given inside of
the class
125
A Class is like an object constructor, or a "blueprint" for creating objects.
Methods in Classes
Define a method in a class by including function definitions within the scope of the
class block
There must be a special first argument self in all of method definitions which gets
bound to the calling instance
There is usually a special method called init in most classes
class student:
self.full_name = n
self.age = a
return self.age
Define class:
Define a method:
Self
The first argument of every method is a reference to the current instance of the class
By convention, we name this argument self
126
In init , self refers to the object currently being created; so, in other class methods,
it refers to the instance whose method was called
Similar to the keyword this in Java or C++
But Python uses self-more often than Java uses this
You do not give a value for this parameter (self) when you call the method, Python
will provide it.
Although you must specify self explicitly when defining the method, you don’t
include it when calling the method.
Python passes it for you automatically
Defining a method:
self.age = num
Calling a method:
When you are done with an object, you don’t have to delete or free it explicitly.
Python has automatic garbage collection.
Python will automatically detect when all of the references to a piece of memory have
gone out of scope. Automatically frees that memory.
Generally works well, few memory leaks
There’s also no “destructor” method for classes
f = student(“Python”, 14)
result: “Python”
result: 14
Example
127
Delete the age property from the f object:
del f.age
Encapsulation/Data Abstraction
Inheritance
Polymorphism
1. Encapsulation/Data Abstraction
class Encapsulation(object):
self.public = a
self._protected = b
self. private = c
The following interactive sessions shows the behaviour of public, protected and private
members:
128
>>> x = Encapsulation(11,13,17)
>>> x.public
Result: 11
>>> x._protected
Result :13
>>> x._protected = 23
>>> x._protected
Result : 23
>>> x. private
Result error: Traceback (most recent call last): File "<stdin>", line 1, in <module>
AttributeError: 'Encapsulation' object has no attribute ' private‘
The following table shows the different behaviour Public, Protected and Private Data
129
1. Encapsulation/Data Abstraction
INPUT:
OUTPUT:
130
2. Inheritance
Inheritance is a powerful feature in object oriented programming
It refers to defining a new class with little or no modification to an existing
class.
The new class is called derived (or child) class and the one from which it
inherits is called the base (or parent) class.
Derived class inherits features from the base class, adding new features to it.
This results into re-usability of code.
Syntax:
class Baseclass(Object):
body_of_base_class
class DerivedClass(BaseClass):
body_of_derived_class
Example:
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
x = Student("Mike", "Olsen")
x.printname()
2.Inheritance:
131
INPUT:
OUTPUT:
132
1. Polymorphism
Polymorphism in Latin word which made up of ‘ploy’ means many and ‘morphs’
means forms
From the Greek , Polymorphism means many(poly) shapes (morph)
This is something similar to a word having several different meanings depending on
the context
Generally speaking, polymorphism means that a method or function is able to cope
with different types of input.
In OOP , Polymorphism is the characteristic of being able to assign a different
meaning to a particular symbol or operator in different contexts specifically to allow
an entity such as a variable, a function or an object to have more than one form.
Operator Overloading
Python operators work for built-in classes. But same operator behaves differently with
different types.
For example, the + operator will, perform arithmetic addition on two numbers, merge
two lists and concatenate two strings. This feature in Python, that allows same operator
to have different meaning according to the context is called operator overloading
133
Code 1:
# Program to understand class, object and method
def init (self, name, age): #use of init function to assign value to name and age
self.name = name
self.age = age
Output:
134
Polymorphism (CODE 1):
INPUT:
OUTPUT:
135
Code 2:
# Program to understand class, object and method
class Person:
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
x = Person("John", "Doe")
x.printname()
Output:
John Doe
136
Polymorphism (CODE 2):
INPUT:
OUTPUT:
137
Experiment Number: 10
Name of Experiment:
138
Program No. 10
Programs to understand different file handling
operations
Aim: Programs to understand different file handling operations
a) Program to understand file open/read/close functions
b) Program to understand file write/append/create/delete functions
Theory:
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.
In this experiment, we will be focusing on opening, closing, reading and writing data in a
text file.
File Access Modes
Access modes govern the type of operations possible in the opened file. It refers to how the
file will be used once it is 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. There are 6 access modes in python.
1. 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.
2. 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.
3. Write Only (‘w’): Open the file for writing. For existing file, the data is truncated and
over-written. The handle is positioned at the beginning of the file. Creates the file if the
file does not exists.
4. Write and Read (‘w+’): Open the file for reading and writing. For existing file, data is
truncated and over-written. The handle is positioned at the beginning of the file.
5. Append Only (‘a’): Open the file for 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.
139
6. 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.
7. Create(‘x’): Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
Syntax:
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
f = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Note: Make sure the file exists, or else you will get an error.
140
a) Open a file located in the same folder as Python:
Assume that we have following file ‘demofile.txt’ located in same folder as Python
demofile.txt
The open() function returns a file object, which has a read() method for reading the
content of the file:
Example:
f = open("demofile.txt", "r")
print(f.read())
If the file is located in a different location, you will have to specify the file path, like this:
Example:
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
Example
f = open("demofile.txt", "r")
print(f.read(5))
d) Reading lines
You can return one line by using the readline() method:
Example
141
f = open("demofile.txt", "r")
print(f.readline())
By calling readline() two times, you can read the two first lines:
Example
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
By looping through the lines of the file, you can read the whole file, line by line:
Example
f = open("demofile.txt", "r")
for x in f:
print(x)
142
a) Open a file located in the same folder as Python:
INPUT:
OUTPUT:
143
2) Closing files
It is a good practice to always close the file when you are done with it.
Example
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Note: You should always close your files, in some cases, due to buffering, changes made to
a file may not show until you close the file.
Program Code:
f=open('demofile.txt','r')
print(f.read())
print(“Reading welcome.txt”)
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
144
2)Closing files
It is a good practice to always close the file when you are done with it.
Example
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Note: You should always close your files, in some cases, due to buffering, changes made to
a file may not show until you close the file.
Program Code:
f=open('demofile.txt','r')
print(f.read())
print(“Reading welcome.txt”)
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
145
146
This file is located in a folder named “myfiles”, on the D drive. Good
Luck!
Hello
Good Luck!
147
2. Closing files:
INPUT:
148
OUTPUT:
149
b) Program to understand file write/append/create/delete functions
Theory:
To write to an existing file, you must add a parameter to the open() function:
Example
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
print(“overwriting file”)
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
150
b) Create a New File
To create a new file in Python, use the open() method, with one of the following
parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example
f = open("myfile.txt", "x")
c) Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:
Example
import os
os.remove("demofile.txt")
To avoid getting an error, you might want to check if the file exists before you try to delete
it:
Example
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
151
Delete Folder
Example
import os
os.rmdir("myfolder")
152
Code:
f = open("demofile2.txt", "a")
f.close()
f = open("demofile2.txt", "r")
print(f.read())
print(“overwriting file”)
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
Output:
overwriting file
Woops! I have deleted the content!
153
b) Program to understand file
write/append/create/delete functions Theory:
INPUT:
OUTPUT:
154