Unit 4 - Files - OOP
Unit 4 - Files - OOP
Files ,
Object Oriented Programming
Reference Textbook:
Gowrishankar S
Files : topics under this
• File Types;
• Operations on Files–
– Create,
– Open,
– Read,
– Write,
– Close Files;
• File Names and Paths;
• Format Operator.
Note: refer all programs given in class and from journal
FILES
• A file is the common storage unit in a computer, and
all programs and data are “written” into a file and
“read” from a file.
• Every file has a filename and extension (Hello.docx) .
• The file extension helps your computer’s operating
system, like Windows, determine which program will
be associated with the file.
• Files contain data and directories contain groups of
files and organize them on the hard disk.
• Directories dont occupy space but files occupy from
few bytes to GB.
Types of files
• There are 2 types of files in python
1) Text files
2) Binary files
1) Text files :
• Text files contain only textual data
• A typical plain text file contains several lines of text that
are each followed by an End-of-Line (EOL) character.
• An End-of-File (EOF) marker is placed after the final
character, which signals the end of the file.
• Text files include a character encoding scheme that
determines how the characters are interpreted and what
characters can be displayed.
• Common text editors are Notepad, wordpad, textedit etc
• Common extensions for text file formats:
– Web standards: html, xml, css, svg, json,...
– Source code: c, cpp, h, cs, js, py, java, rb, pl, php,
sh,...
– Documents: txt, tex, markdown, asciidoc, rtf, ps,...
– Configuration: ini, cfg, rc, reg,...
– Tabular data: csv, tsv,..
2) Binary files:
• Binary files typically contain a sequence of bytes
or ordered groupings of eight bits.
• Binary file format can store multiple types of
data like images, audio, video in a single file.
• This data can be interpreted by supporting
programs but will show up as garbled text in a
text editor.
• Binary files contain headers in readable form
that give information about file type and other
description. If the header contains invalid data
then the file becomes corrupt or cannot be
opened.
• Common extensions for binary file formats:
– Images: jpg, png, gif, bmp, tiff, psd,...
– Videos: mp4, mkv, avi, mov, mpg, vob,...
– Audio: mp3, aac, wav, flac, ogg, mka, wma,...
– Documents: pdf, doc, xls, ppt, docx, odt,...
– Archive: zip, rar, 7z, tar, iso,...
– Database: mdb, accde, frm, sqlite,...
– Executable: exe, dll, so, class,...
File paths
• File path is basically a route so that the user or
the program knows where the file is located.
• To use files we must specify its path
• The path to a specified file consists of one or
more components, separated by a special
character (a backslash for Windows and forward
slash for Linux).
• each component is usually a directory name or
file name, or drive name in Windows or root in
Linux.
• example: D:\\myfiles\python\home.py
There are 2 types of file paths : Fully qualified and
Relative
• Fully qualified file path (Absolute path) :
– it points to the file location, which always contains the root and the
complete directory list.
– The current directory is the directory in which a user is working at a
given time.
– Example : D:\\myfiles\python\home.py or D:\\ welcome.txt
• Relative path :
– It consists of two consecutive dots or a single dot as one of the
components in a path.
– These dots denote the directory above the current directory (parent
directory)
– Example : ..\home.py or ..\..\home.py or .\home.py
Different operations on files and their
respective functions
1) Open a file open() , with open()
2) Read data from file read() , readline(),
readlines()
3) Write data to a file write() , writelines()
4) Close a file close()
5) Delete a file os.remove()
6) Move the file handler seek()
7) display the current position of file handler
tell()
1. Creating and opening text files
• Before we perform any read or write operation , we
must open the file using the python builtin function
open() .
• When a file is opened using open() function, it returns a
file object called a file handler that provides methods for
accessing the file.
• Open() takes two parameters filename and mode
• Syntax:
file_handler_object = open(filename, mode)
example: fp = open(“hello.txt”, “r”)
file_handler = open("C:\prog\example.txt",“w")
• Example:
file_handler = open("C:\prog\example.txt","r")
file_handler = open("C:\\fauna\\bison.txt","r")
file_handler = open("C:\\network\computer.txt","r")
file_handler = open(r"C:\network\computer.txt","r“)
File modes
Modes Description
“r” Opens the file in read only mode and
this is the default mode.
“w” Opens the file for writing. If a file
already exists, then it’ll get
overwritten. If the file does not exist,
then it creates a new file.
“a” Opens the file for appending data at
the end of the file automatically. If
the file does not exist it creates a new
file.
“r+” Opens the file for both reading and
writing.
“w+” Opens the file for reading and writing.
If the file does not exist it creates a
new file. If a file already exists then it
will get overwritten.
Modes Description
“a+” Opens the file for reading and appending.
If a file already exists, the data is
appended. If the file does not exist it
creates a new file.
“x” Creates a new file. If the file already
exists, the operation fails.
f = open('workfile', 'w')
f.write('0123456789abcdef')
f.close()
f = open('workfile', 'r')
print("file contents are: ")
print(f.read())
f.seek(2)
print("reading data starting at 2 bytes from 0 position:",f.read())
print("current position of file handler is :")
print(f.tell())
f.close()
Object Oriented Programming
1. Classes and Objects;
2. Creating Classes and Objects;
3. Constructor Method;
4. Classes with Multiple Objects;
5. Objects as Arguments;
6. Objects as Return Values;
7. Encapsulation- Definition, Private Instance Variables;
8. Inheritance-
A. Single
B. Multiple Inheritance,
C. Multilevel
D. Multipath Inheritance;
9. Polymorphism- Definition, Operator Overloading.
Object-oriented programming (OOP)
• In Object-oriented programming (OOP) we use
objects to model real-world things that we want to
represent inside our programs and provide a simple
way to access their functionality.
• Advantages of Object-oriented programs are :
– easier to modify
– requires less work to maintain over time.
– code reuse,
– cleaner code,
– better architecture,
– abstraction layers,
– fewer programming bugs.
• Python supports encapsulation , inheritance and
polymorphism.
What is OOP ?
easy explanation by Steve Jobs in an old
interview
• https://youtu.be/9CZFrneaASM
1. Classes and Objects
• A class is a blueprint from which individual
objects are created.
• An object is a instance of a class or it is a
bundle of related state (variables or data
members ) and behavior (methods or
functionality).
Generic object diagram
2. Creating classes and objects in
python
• Classes are defined by using the class keyword, followed by
the ClassName and a colon. Class definitions must be
executed before they have any effect.
• the statements inside a class definition will usually be
function definitions (methods of class)
• Syntax:
class classname:
<statement 1>
<statement 2>
--------------
<statement n>
Creating objects or Class instantiation in python:
• The syntax for object creation is,
object_name = ClassName(argument_1, argument_2, …..,
argument_n)
• The syntax to access data attribute is,
object_name . data_attribute_name
MOBILE
Methods
APPLEMOB Send_message()
Receive_message()
#class definition
class Mobile:
#constructor method
def __init__(self):
print("This message is from Constructor Method")
#method 1
def receive_message(self):
print("Receive message using Mobile")
#method 2
def send_message(self):
print("Send message using Mobile")
#main function
def main():
applemob = Mobile() #create an object called applemob
applemob.receive_message() # call the method
applemob.send_message() # call the method
if __name__ == "__main__":
main()
Example – create class called mobile with attribute mobile name
, two methods and object called applemob
MOBILE
DataAttributes
Mobile_name
Methods
APPLEMOB
Send_message()
Receive_message()
#class definition
class Mobile:
#constructor method
def __init__(self, name):
print(f"object is {self}")
self.mobile_name = name #assign name parameter to data attribute
#method1
def receive_message(self):
print(f"Receive message using {self.mobile_name} Mobile")
#method2
def send_message(self):
print(f"Send message using {self.mobile_name} Mobile")
def main():
vulture = Birds("Griffon Vulture") #object 1
emu = Birds("Emu") #object2
vulture.flying_birds() #object 1 method 1
emu.non_flying_birds() #object 2 method 2
if __name__ == "__main__":
main()
5. Objects as Arguments
• An object can be passed to a calling function (defined outside class )
as an argument.
#objects as argument to a function
class Track:
def __init__(self, song, artist):
self.song = song
self.artist = artist
• The id() function is used to find the identity of the location of the
object in memory.
syntax for id() function is,
id(object)
• Also we check whether an object is an instance of a given class or
not.
Syntax : isinstance (object, classinfo)
• Everything in python, almost everything is an object.
Lists, dictionaries, tuples are also python objects.
• The code below shows a python function that
returns a python dictionary.
# This function returns a dictionary
def foo():
d = dict();
d['str'] = “welcome"
d['x'] = 50
return d
print foo()
7. Encapsulation
• Encapsulation is the process of combining
variables that store data and methods that work
on these variables into a single unit called class.
• Encapsulation ensures that the object’s internal
representation (its state and behavior) are hidden
from the rest of the application thus promoting
data hiding.
• The variables are not accessed directly; it is
accessed through the methods present in the
class.
• Abstraction is a process which shows only
“relevant” variables that are used to access data
and “hide” implementation details of an object
from the user.
• An application using a class does not need to
know its internal workings or how it is
implemented. The program simply creates an
object and uses it to invoke the methods of that
class.
• Encapsulation promotes data hiding
• Abstraction promotes implementation hiding
Using private instance variables and methods
and Name Mangling
• Instance variables or methods, which can be accessed within the
same class and can’t be seen outside, are called private instance
variables or private methods.
• Name mangling:
– In Python, mangling is used for class attributes that one does not
want subclasses to use
– Name mangling is the encoding of function and variable names into
unique names so that linkers can separate common names in the
language.
– On encountering a mangled variable , python will replace it with one
trailing underscore and two leading underscores
__ClassName__Identifier
– It allows different entities to be named with the same identifier as
long as they occupy a different namespace or have
different signatures
#example on name mangling
class myClass:
def __init__(self):
self.x=10
self.__y=20
obj=myClass()
print(obj.x) #shows value 10
print(obj.__y) #shows error because it is a mangled variable
8. Inheritance
• Inheritance enables new classes to receive or
inherit variables and methods of existing classes.
• Thus the new class extends the features of
existing class by adding some new functionality.
• A class that is used as the basis for inheritance is
called a superclass or base class.
• A class that inherits from a base class is called a
subclass or derived class.
• Inheritance easily enables reusing of existing
code.
• Relationship between base class and derived class is
represented using is-a relationship .
• example: lemon is-a citrus fruit, which is-a fruit
• Syntax to define derived class
class DerivedClassName(BaseClassName):
<statement 1>
----------------
<statement n>
• example:
class fruit:
print(“this is base class fruit”)
class citrusfruit(fruit):
print(“this is derived class citrus fruit “)
#derived class
class WorldChampions(FootBall):
def world_championship(self):
print(f"{self.country} national football team is {self.no_of_times} times world champions")
def main():
germany = WorldChampions("Germany", "UEFA", 4)
germany.fifa()
germany.world_championship()
if __name__ == "__main__":
main()
Super() function
• The super() function is used to give access to
methods and properties of a parent or sibling
class. Hence a method from parent class can be
called using a super()
• The super() function returns an object that
represents the parent class.
• syntax:
super().__init__(base_class_parameter(s))
class Fiction(Book):
def __init__(self, author, title, publisher):
super().__init__(author, title)
self.publisher = publisher
def book_info(self): #derived class method
print(f"{self.title} is authored by {self.author} and published by
{self.publisher}")
def invoke_base_class_method(self):
super().book_info() # calls base class method
#main function continued
def main():
print("Derived Class")
book1 = Fiction("RK narayan", "Swami and friends", "Mysore
publications")
book1.book_info() #calls derived class bookinfo with book1 obj
class ICICI(Bank):
def getroi(self):
return 8;
b1 = Bank()
b2 = SBI()
b3 = ICICI()
print("Bank Rate of interest:",b1.getroi());
print("SBI Rate of interest:",b2.getroi());
print("ICICI Rate of interest:",b3.getroi());
B) Multiple inheritance
Theory Practical
FinalGrade
EMPLOYEE
SALARY
DESIGNATION
#multilevel inheritance
class Employees():
def display_Name(self):
print("Employee Name: Khush")
class Salary(Employees):
def display_Sal(self):
print("Salary: 10000")
class Designation(Salary):
def display_desig(self):
Employees.display_Name(self)
Salary.display_Sal(self)
print("Designation: Test Engineer")
class C(A):
def target(self):
print("Invoked method in class C")
super().target()