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

Python Exp No. 9 and 10

The document outlines Experiment Number 09, which focuses on understanding Object-Oriented Programming (OOP) concepts such as classes, objects, and methods using Python. It explains the features of OOP, the differences between procedural and object-oriented programming, and details about classes, methods, and fundamental OOP principles like encapsulation, inheritance, and polymorphism. Additionally, it includes code examples to illustrate these concepts and prepares for a subsequent experiment on file handling operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Python Exp No. 9 and 10

The document outlines Experiment Number 09, which focuses on understanding Object-Oriented Programming (OOP) concepts such as classes, objects, and methods using Python. It explains the features of OOP, the differences between procedural and object-oriented programming, and details about classes, methods, and fundamental OOP principles like encapsulation, inheritance, and polymorphism. Additionally, it includes code examples to illustrate these concepts and prepares for a subsequent experiment on file handling operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Experiment Number: 09

Name of Experiment: Programs to understand Object


oriented Programming (OOP) concepts: classes, objects
and methods

Date of Perfomance : /0 /2025

Date of Submission : /0 /2025

123
Experiment No. 9
Programs to understand Object oriented Programming
(OOP) concepts: classes, objects and methods
Aim: To study classes, objects and methods

Theory:

Python is an object oriented programming (OOP) language. Almost everything in Python is


an object, with its properties and methods.

Features of OOP

 Ability to simulate real-world event much more effectively

 Code is reusable thus less code may have to be written

 Data becomes active

 Better able to create GUI (graphical user interface) applications

 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

Difference between Procedure Oriented and Object Oriented Programming

 Procedural programming creates a step by step program that guides the


application through a sequence of instructions. Each instruction is executed in
order.

 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.

 Objects have two components: - Data (i.e., attributes)

- Behaviours (i.e., methods)

Object Attributes and Methods Example (Taxi)

Object Attributes Store the data for that object

Driver

OnDuty ,

NumPassengers

Location

Object Methods Define the behaviours for the object

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

 Python doesn’t use separate class interface definitions as in some languages

 You just define the class and then use it

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

A Simple Class Example:

class student:

“””A class representing a student”””

def init (self , n, a):

self.full_name = n

self.age = a

def get_age(self): #Method

return self.age

Define class:

 Class name, begin with capital letter, by convention


 object: class based on (Python built-in type)

Define a method:

 Like defining a function


 Must have a special first parameter, self, which provides way for a method to refer
to object itself

Instantiating Objects with ‘__init__’

 init is the default constructor


 init serves as a constructor for the class. Usually does some initialization work
 An init method can take any number of arguments
 However, the first argument self in the definition of init is special

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:

(this code inside a class definition.)

def get_age(self, num): #define a method get_age

self.age = num

Calling a method:

x. get_age(23) #calling method get_sge

Deleting instances: No Need to “free”

 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

Syntax for accessing attributes and methods

f = student(“Python”, 14)

f.full_name # Access attribute

result: “Python”

f.get_age() # Access a method

result: 14

Delete Object Properties

You can delete properties on objects by using the del keyword:

Example

127
Delete the age property from the f object:

del f.age

Fundamental concepts of OOP in Python

The four major principles of object orientation are:

 Encapsulation/Data Abstraction
 Inheritance
 Polymorphism

1. Encapsulation/Data Abstraction

Encapsulation is the mechanism for restricting the access to some of an objects's


components, this means, that the internal representation of an object can't be seen from
outside of the objects definition. The terms encapsulation and abstraction (also data
hiding) are often used as synonyms. They are nearly synonymous, i.e. abstraction is
achieved though encapsulation.

Public, Protected and Private Data

 If an identifier doesn't start with an underscore character "_" it can be accessed


from outside, i.e. the value can be read and changed
 Data can be protected by making members private or protected. Instance variable
names starting with two underscore characters cannot be accessed from outside of
the class.
 At least not directly, but they can be accessed through private name mangling.
 That means, private data A can be accessed by the following name construct:
instance_name._classname A
 If an identifier is only preceded by one underscore character, it is a protected
member.
 Protected members can be accessed like public members from outside of class
Example:

class Encapsulation(object):

def init (self, a, b, c):

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

Name Notation Behaviour

Name Public Can be accessed from inside and outside

_name Protected Like a public member, but they shouldn't be


directly accessed from outside

name private Can't be seen and accessed from outside

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:

class Person: #base class(parent class)

def init (self, fname, lname):

self.firstname = fname

self.lastname = lname

def printname(self):

print(self.firstname, self.lastname)

class Student(Person): #derived class/child class

pass #inherits method and properties from base class

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

class Person: #create class named Person

def init (self, name, age): #use of init function to assign value to name and age

self.name = name

self.age = age

def myfunc(self): #object method/function named myfunc

print("Hello my name is " , self.name)

p1 = Person("John", 36) #create object p1

p1.myfunc() #calling method myfunc

Output:

Hello my name is John

134
Polymorphism (CODE 1):

INPUT:

OUTPUT:

135
Code 2:
# Program to understand class, object and method

class Person:

def init (self, fname, lname):

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:

Programs to understand different file handling


operations

Date of Perfomance : /04/2025

Date of Submission : /04/2025

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

a) Program to understand file open/read and close

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

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

1. Open a file for Reading:

Syntax:

To open a file for reading it is enough to specify the name of the file:

f = open("demofile.txt")

The code above is the same as:

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

Hello! Welcome to demofile.txt


This file is for testing purposes.
Good Luck!

To open the file, use the built-in open() function.

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())

b) Open a file which is located in different location:

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())

c) Reading Only Parts of the File


By default the read() method returns the whole text, but you can also specify how many
characters you want to return:

Example

Return the 5 first characters of the file:

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

Read two lines of the file:

f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())

e) Reading whole file line by line

By looping through the lines of the file, you can read the whole file, line by line:

Example

print(“Loop through the file line by line”)

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

Close the file when you are finish with it:

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:

#Open a file in read mode. File is in same folder as Python


print(“Reading demofile.txt”)

f=open('demofile.txt','r')

print(f.read())

#Open a file located in different location

print(“Reading welcome.txt”)

f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())

# Read first 5 first characters of the file

print(“Reading first 5 characters from demofile”)

144
2)Closing files

It is a good practice to always close the file when you are done with it.

Example

Close the file when you are finish with it:

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:

#Open a file in read mode. File is in same folder as Python


print(“Reading demofile.txt”)

f=open('demofile.txt','r')

print(f.read())

#Open a file located in different location

print(“Reading welcome.txt”)

f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())

# Read first 5 first characters of the file

print(“Reading first 5 characters from demofile.

145
146
This file is located in a folder named “myfiles”, on the D drive. Good

Luck!

Reading first 5 characters from demofile

Hello

Reading first line from demofile

Hello! Welcome to demofile.txt

Reading first two lines from demofile

Hello! Welcome to demofile.txt

This file is for testing purposes.

Loop through the file line by line

Hello! Welcome to demofile.txt

This file is for testing purposes.

Good Luck!

147
2. Closing files:

INPUT:

148
OUTPUT:

149
b) Program to understand file write/append/create/delete functions

Theory:

a) Write to an Existing File

To write to an existing file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content.

Example

Open the file "demofile2.txt" and append content to the file:

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())

Open the file "demofile3.txt" and overwrite the content:

print(“overwriting file”)

f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the appending:


f = open("demofile3.txt", "r")
print(f.read())
Note: the "w" method will overwrite the entire file.

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

Create a file called "myfile.txt":

f = open("myfile.txt", "x")

Result: a new empty file is created!

c) Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:

Example

Remove the file "demofile.txt":

import os

os.remove("demofile.txt")

Check if File exist:

To avoid getting an error, you might want to check if the file exists before you try to delete
it:

Example

Check if file exists, then delete it:

import os

if os.path.exists("demofile.txt"):

os.remove("demofile.txt")

else:

print("The file does not exist")

151
Delete Folder

To delete an entire folder, use the os.rmdir() method:

Example

Remove the folder "myfolder":

import os

os.rmdir("myfolder")

Note: You can only remove empty folders.

152
Code:

#appending content to the file

f = open("demofile2.txt", "a")

f.write("Now the file has more content!")

f.close()

#open and read the file after the appending:

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()

#open and read the file after the appending:


f = open("demofile3.txt", "r")
print(f.read())

# create new file


f = open("myfile.txt", "w")

Output:

Hello! Welcome to demofile2.txt

This file is for testing purposes.

Good Luck!Now the file has more content!

overwriting file
Woops! I have deleted the content!

153
b) Program to understand file
write/append/create/delete functions Theory:

INPUT:

OUTPUT:

154

You might also like