Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 85

UNIT – 3

Contents:
 Advance Python- OOPs concept
Class and object, Attributes, Inheritance, Overloading Overriding,
Data hiding.
 Regular expressions
Match function, Search function, Matching VS Searching, Modifiers
Patterns.
Files and Directories:
File Handling, working with File Structure, Directories, Handling
Directories
Class and object

 A user-defined prototype for an object that defines a set of


attributes that characterize any object of the class.
 The attributes are data members (class variables and instance
variables) and methods, accessed via dot notation.

Syntax

class ClassName:
'Optional class documentation string'
class_suite

 The class has a documentation string, which can be accessed via


ClassName.__doc__.
 The class_suite consists of all the component statements defining
class members, data attributes and functions.
Ex
Class Student:
def __init__(self):
self.name=‘John’
self. age=20
self.marks=900
def talk(self):
print(“Hi, I am”,self.name)
print(“my age is”,self.age)
print(“my marks are”,self.marks)
 A class is created by using the keyword class.
 A class describes attributes and actions performed by its objects.
 class name should start with a capital letter.
 __init__(self) is a special method to initialize the variables.
 self is a variable refer to the current class instance.
 An object is a instance of a class. To use a class we have to create an
instance.
instance name=classname()
s1=Student()
Attributes
Python has two types of attributes
 Class attributes
 Instance attributes
Class / static attributes

 The variables which are declared within the class outside the
methods are known as static variables
 The data which is common for all the objects is recommended to
represent by using static variables.
 For all the static variables of a class memory will be allocated only
once.
 Static variables of one class we can access within same class by
using class name or by using self
 Static variables of one class we can access outside of the class by
using class name or by using reference variable name.
Ex output
class x: 1000
a=1000 in m1 of x
def m1(self) 1000
print(x.a) in m2 of x
print(“in m1 of x”) 1000
def m2(self) 1000
print(self.a)
print(“in m2 of x”)
X1=x()
X1.m1()
X1.m2()
print(x.a)
print(x1.a)
Instance / nonstatic attributes
 Variables which are declared within the class by using self or by
using reference variable are known as non static variables
 The data which is separate for every object is recommended to
represent by using non static variables
 Non static variables of a class memory will be allocated within the
object.
 We can create n number of objects for a class so that n number of
times memory will be allocated for non static variables
 Non static variables of a class we can access within the same class
by using self. Or by using reference variable.
Ex: Output:
class x: 1000
def m1(self): 2000
self.a=1000 3000
self.b=2000 4000
def display(self): 1000
print(self.a) 2000
print(self.b)
X1=x()
X1.m1()
X1.display()
X1.a=3000
X1.b=4000
X1.display()
X2=x()
X2.m1()
X2.display()
Python In-built class functions
SN Function Description
1 getattr(obj,name,default) It is used to access the attribute of the
object.

2 setattr(obj, name,value) It is used to set a particular value to the


specific attribute of an object.

3 delattr(obj, name) It is used to delete a specific attribute.

4 hasattr(obj, name) It returns true if the object contains some


specific attribute.
Ex
class Student:  
def __init__(self,name,id,age):  
self.name = name  
self.id = id  
self.age = age  
s = Student("John",101,22)  #creates the object of the class Student  
print(getattr(s,'name'))  #prints the attribute name of the object s
setattr(s,"age",23)   # reset the value of attribute age to 23  
print(getattr(s,'age'))  # prints the modified value of age  
print(hasattr(s,'id'))   # prints true if the student contains the attribute 
with name id 
delattr(s,'age')   # deletes the attribute age  
print(s.age)  # this will give an error since the attribute age has 
been deleted  
output
John
23
True
AttributeError: 'Student' object has no attribute 'age'
Built-in class attributes
A python class also contains some built-in class attributes which
provide information about the class.
SN Attribute Description
1 __dict__ It provides the dictionary containing the information
about the class namespace.

2 __doc__ It contains a string which has the class documentation

3 __name__ It is used to access the class name.


4 __module__ It is used to access the module in which, this class is
defined.
5 __bases__ It contains a tuple including all base classes.
EX
class Student:  
def __init__(self,name,id,age):  
self.name = name 
self.id = id
self.age = age  
def display_details(self):  
print("Name:%s, ID:%d, age:%d"%(self.name,self.id))  
s = Student("John",101,22)  
print(s.__doc__)  
print(s.__dict__)  
print(s.__module__)  
Output 
None
{'name': 'John', 'id': 101, 'age': 22}
__main__
Inheritance
 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.
 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.
Syntax
class  derived-class(base class):  
<class-suite>   
 In python, a derived class can inherit base class by just mentioning
the base in the bracket after the derived class name.
 A class which is extended by another class is known as a super class
or base class
 A class which is extending another class is known as a sub class or
derived class
Single Inheritance
The concept of inheriting the properties from only one class into
another class.
Ex
class A:
def m1(self):
print(“m1 method”)
class B(A):
def m2(self):
print(“m2 method”)
b=B()
b.m1()
b.m2()
Multilple Inheritance

The features of all the base classes are inherited into the derived class.
Ex
class x:
def m1(self): Output
print(“in m1 of x”) in m1 of x
class y: in m2 of y
def m2(self): in m3 of z
print(“in m2 of y”)
class z(x,y):
def m3(self):
print(“in m3 of z”)
z1=z()
z1.m1()
z1.m2()
Z1.m3()
Multilevel Inheritance
The features of the base class and the derived class is inherited into
the new derived class.
Ex
class X:
def m1(self):
print(“in m1 of x”)
class Y(X):
def m2(self):
print(“in m2 of y”)
class Z(Y):
def m3(self):
print(“in m3 of z”)
Z1=Z()
Z1.m1()
Z1.m2()
Z1.m3()
Overloading and Overriding
Overloading
Defining multiple methods with the same name with different
number of parameters with in the same class or one is in super class and
other is in sub class.
Ex
class X:
def product(a,b):
p=a*b
print(p)
def product(a,b,c):
p=a*b*c
print(p)
X1=X()
X1.product(4,5) # produces an error
 python doesn’t support method overloading but we can make the
same function work differently that is as per the arguments.
EX
class X:
def m(self,*args):
self.j=1
for i in args:
self.j=self.j*i
print(self.j)
X1=X()
X1.m(10,20)
X1.m(2,3,4)
Overriding
 The parent class method is defined in the child class with some
specific implementation, then the concept is called method overriding.
 We may need to perform method overriding in the scenario where
the different definition of a parent class method is needed in the child
class.
Ex
class Parent:  
def speak(self):  
print("speaking telugu")  
class Child(Parent):  
def speak(self):  
print(“speaking english")  
c = Child()  
c.speak()  
Data hiding
 Abstraction is an important aspect of object-oriented programming.

 In python, we can also perform data hiding by adding the double


underscore (___) as a prefix to the attribute which is to be hidden.
 After this, the attribute will not be visible outside of the class
through the object.
Ex
class My class:
def __init__(self):
self.__y=3
m=Myclass()
print(m.y) # produces an error ie; Attribute Error
Regular expressions
 A Regular Expression is a string that contains symbols and
characters to find and extract the information needed by us.
 A Regular expression helps us to search information, match, find
and split information as per our requirements.
 It is also called regex.
 python provides re module, it contains the methods like compile(),
search(), match(), findall(), split() etc are used in finding the information
in the available data.
The Regular Expressions are used to perform the following
operations.
 Matching strings
 Searching for strings
 Finding all strings
 Splitting a string into pieces
 Replacing strings
 The match() method searches in the beginning of the string
and if the matching string is found, it returns a object that contains
the resultant string, otherwise returns None. We can access the
returned object using group() method.
 The search() method searches the string from beginning till the
end and returns the first occurrence of the matching string
otherwise returns None. group() method is used to retrieve the
string.
 The findall() method splits the string according to regular
expression and returns list object, otherwise returns empty list,
retrieve the result using for loop.
Sequence characters in Regular Expressions
Character Description
\d represents any digit(0-9)
\D represents any non digit
\s represents white space(\t,\n)
\S represents non whitespace
\w represents any alphanumeric(A-Z,a-z,0-9)
\W represents any non alphanumeric
\b represents a space around words
\A matches only at start of the string
\z matches only at end of the string
Modifiers in Regular Expressions
Quantifiers in Regular Expressions
Character Description
+ one or more occurrences of the preceding expression
* Zero or more repetitions of the preceding expression
? Zero or one repetition of the preceding expression
{m} Exactly m occurences
{m,n} from m to n, m defaults to 0, n to infinity
Special characters
Character Description
\ escape special characters nature
. Matches any character except new line
^ matches beginning of a string
$ matches end of a string
[…] set of possible characters.
[^…] matches every character except the ones inside brackets
(…) matches the regular expression inside the parenthesis
R|S matches either regex R or regex S
Programs using match() function
Ex 1
import re
line = "Every thing is planned"
patten ='Every'
m =re.match(patten,line)
if m:
print("matched at the starting")
print (m.group())
else:
print("not matched")
EX 2
import re
str = “man sun mop run”
result= re.match(r’m\w\w’,str)
print(result.group())
Programs using search() function
EX 1
import re
str=“one two three four five six seven 8 9 10”
result=re.search(r’\b\w{5}\b’,str)
print(result.group())
EX 2
import re
str=“man sun mop run”
result = re.search(r’m\w\w’,str)
if result:
print(result.group())
Ex 3
import re
regex=re.compile(r"\d{10}")
#compile function checks whether the pattern defined correctly or not,
#then it internally creates regex object
while True:
mobno=input("enter mobile number")
if len(mobno)==10:
result=regex.search(mobno)
if result:
print("valid mobile number")
break
else:
print("invalid mobile number")
Ex 4
import re
regex=re.compile(r"(\w+) World")
result=regex.search("Hello world is the easiest World")
if result:
print("match at index",result.start(),result.end())
Ex 5
import re
pattern = "this"
text = "in this world nothing is permanent"
match = re.search(pattern, text)
s = match.start()
e = match.end()
print(s)
print(e)
Modifiers Patterns.
Python File I/O
What is a file?

• File is a named location on disk to store related information.

• It is used to permanently store data in a non-volatile memory


(e.g. hard disk).

• When we want to read from or write to a file we need to open it


first.

• When we are done, it needs to be closed, so that resources that


are tied with the file are freed.
 A File is an external storage on hard disk from
where data can be stored and retrieved.
 A file is a chunk of logically related data or
information which can be used by computer
programs.
 Python provides some basic functions to
manipulate files. Hence, in Python, a file
operation takes place in the following order.
• Open a file
• Read or write (perform operation)
• Close the file
Operations on Files:
• Opening a File:
 Before working with Files you have to open the
File. To open a File, Python built in function open()
is used. It returns an object of File which is used
with other functions.
 Having opened the file now you can perform read,
write, etc. operations on the File.
Example
• f = open("python.txt",'w') # open file in current
directory
f=open("/home/rgukt/Desktop/python/hello.txt")
# specifying full path
How to open a file?

• Python has a built-in function open() to open a


file.

• This function returns a file object, also called a


handle, as it is used to read or modify the file
accordingly.
• We can specify the mode while opening a file. In mode, we
specify whether we want to read 'r', write 'w' or append 'a'
to the file. We also specify if we want to open the file in text
mode or binary mode.

• The default is reading in text mode. In this mode, we get


strings when reading from the file.

• On the other hand, binary mode returns bytes and this is the
mode to be used when dealing with non-text files like image
or exe files.
• f = open("test.txt") # equivalent to 'r' or 'rt'
• f = open("test.txt",'w') # write in text mode
• f = open("img.bmp",'r+b') # read and write in
binary mode
• How to close a file Using Python?
• When we are done with operations to the file, we need to
properly close the file.

• Closing a file will free up the resources that were tied with
the file and is done using Python close() method.

• Python has a garbage collector to clean up unreferenced


objects but, we must not rely on it to close the file.

• f = open("test.txt",encoding = 'utf-8')
• # perform file operations
• f.close()
• This method is not entirely safe. If an exception
occurs when we are performing some operation
with the file, the code exits without closing the file.

• A safer way is to use a try...finally block.

• try:
• f = open("test.txt")
• # perform file operations
• finally:
• f.close()
• This way, we are guaranteed that the file is properly
closed even if an exception is raised, causing program
flow to stop.

• The best way to do this is using the with statement. This


ensures that the file is closed when the block inside with
is exited.

• We don't need to explicitly call the close() method. It is


done internally.

• with open("test.txt",encoding = 'utf-8') as f:


• # perform file operations
How to write to File Using Python?

• In order to write into a file in Python, we need to


open it in write 'w', append 'a' or exclusive creation 'x'
mode.

• We need to be careful with the 'w' mode as it will


overwrite into the file if it already exists. All previous
data are erased.

• Writing a string or sequence of bytes (for binary files)


is done using write() method. This method returns the
number of characters written to the file.
• with open("test.txt",'w') as f:
• f.write("my first file\n")
• f.write("This file\n\n")
• f.write("contains three lines\n")
• This program will create a new file named
'test.txt' if it does not exist. If it does exist, it
is overwritten.

• We must include the newline characters


ourselves to distinguish different lines.
How to read files in Python?

• To read a file in Python, we must open the file


in reading mode.

• There are various methods available for this


purpose.

• We can use the read(size) method to read in


size number of data. If size parameter is not
specified, it reads and returns up to the end of
the file.
• We can see that, the read() method returns
newline as '\n'. Once the end of file is
reached, we get empty string on further
reading.

• We can change our current file cursor


(position) using the seek() method. Similarly,
the tell() method returns our current position
(in number of bytes).
• >>> #Alternately, we can use readline() method to
read individual lines of a file. This method reads a
file till the newline, including the newline
character.

• >>> f.readline()
• 'This is my first file\n'
• >>> f.readline()
• 'This file\n'
• >>> f.readline()
• 'contains three lines\n'
• Lastly, the readlines() method returns a list of
lines of the entire file.
• >>> f.readlines()
• ['This is my first file\n', 'This file\n', 'contains
three lines\n']
62
Basic Input /Output Operations
Python can be used to read and write data. Also it supports reading and
writing data to Files.

“print" statement:

 "print" statement is used to print or display the output on the screen.


 print statement is used to take string as input and place that string to
standard output.
 Whatever you want to display on output place that expression inside
the inverted commas. The expression whose value is to printed place it
without inverted commas.
Syntax: print(“expression”)
Ex: >>> print("Welcome")

63
Input from Keyboard
 Python offers two in-built functions for taking input from user. They
are:
 input( )
 input() function is used to take input from the user. Whatever
expression is given by the user, it is evaluated and result is returned
back.

Syntax: input(“Expression”)

Ex:
>>>n=input("Enter your expression")
Enter your expression 10
>>>print("The evaluated expression is", n)
The evaluated expression is 10

64
raw_input()
 raw_input() function is used to take input from the user. It takes the
input from the Standard input in the form of a string and reads the data
from a line at once.
Syntax:raw_input(“Statement”)
Ex:
n=raw_input(“Enter your name”);
print(“Welcome”,n)
Note:raw_input() function returns a string. Hence incase an expression
is to be evaluated, then it has to be type casted to its following
datatype.

Ex:
prn=int(raw_input("Enter Principal"))
r=int(raw_input("Enter Rate"))
t=int(raw_input("Enter Time"))
si=(prn*r*t)/100
print("Simple Interest is",si) 65
# Program to enter details of an user and print them.

name=raw_input("Enter your name")


math=float(raw_input("Enter your marks in Math"))
physics=float(raw_input("Enter your marks in Physics"))
chemistry=float(raw_input("Enter your marks in Chemistry"))
rollno=int(raw_input("Enter your Roll no"))
print("Welcome", name)
print("Your Roll no is", roll no)
print("Marks in Maths is", math)
print("Marks in Physics is", physics)
print("Marks in Chemistry is", chemistry)
print("Average marks is",(math+ physics+ chemistry)/3)

66
Handling Files & Operations
 Python provides the facility of working on Files.
 File is a named location on disk to store related information. It is used
to permanently store data in a non-volatile memory(e. g. hard disk)
 Since, random access memory(RAM) is volatile which loses its data
when computer is turned off, we use files for future use of the data.
 When we want to read from or write to a file we need to open it first.
When we are done, it needs to be closed, so that resources that are tied
with the file are freed
 A File is an external storage on hard disk from where data can be
stored and retrieved.
 A file is a chunk of logically related data or information which can be
used by computer programs.
 Python provides some basic functions to manipulate files

67
Operations on Files:

Opening a File:
 Before working with Files you have to open the File. To open a File,
Python built in function open() is used. It returns an object of File which
is used with other functions.
 Having opened the file now you can perform read, write, etc.
operations on the File.

Example
f = open("python.txt",'w') # open file in current directory
f = open("/home/rgukt/Desktop/python/hello.txt")
# specifying full path

68
Used to open or create a file
Syntax:
fileObject=open(file_name,access_mode,buffering)
here,
file_name: It is the name of the file which you want to access.
access_mode: It specifies the mode in which File is to be opened.
 There are many types of mode like read, write, append.
 Mode depends the operation to be performed on File.
 Default access mode is read.
buffering:
 If the buffering value is set to 0, no buffering takes place.
 If the buffering value is 1, line buffering is performed while
accessing a file

69
Closing a File:
 Once you are finished with the operations on File at the end you
need to close the file.
 It is done by the close( ) method. close( ) method is used to close a
File.
Syntax: file object. close( )

Writing to a File:
 write() method is used to write a string into a file.
 Strings can have binary data or text data
 Syntax: fileobject.write(string)

Reading from a File:


 read() method is used to read data from the file.
 Parameter “count” is the number of bytes to be read from the
opened file
Syntax: fileobject.read(count)
Append Mode: Syntax: fileobject.open(“filename”,  "a”) 70
# Program to read and write data from a file.
obj=open("abcd.txt","w")
obj.write("Welcome to the world of Python\n Yeah its great\n")
obj.close()
obj1=open("abcd.txt","r")
s=obj1.read( )
print (s )
obj1.close()
obj2=open("abcd.txt","r")
s1=obj2.read(20)
print (s1 )
obj2.close()

71
Ex: 2
f=open("test.txt","w")
f.write("my first file\n")
f.write("This file\n\n")
f.write("contains three lines\n")
f.write('''hello
this is
first program
in files''')#we can write multiple lines
f.close()

72
append mode
 Open for appending at the end of the file without truncating it.
Creates a new file if it does not exist.

Example

f = open("try.txt","a")
f.writelines("hello\nhi\nhow\n")
f.writelines("hello\nhi\nhow\n")
f.close()

73
read mode
 To read the content of a file, we must open the file in reading mode.
There are various methods available for this purpose. We can use the
read(size)method to read in size number of data. If size parameter is not
specified, it reads and returns up to the end of the file.
Example

f=open("test.txt",'r')
print(f.read(4))
print(f.read())

74
read mode
 To read the content of a file, we must open the file in reading mode.
There are various methods available for this purpose. We can use the
read(size)method to read in size number of data. If size parameter is not
specified, it reads and returns up to the end of the file.
Example

f=open("test.txt",'r')
print(f.read(4))
print(f.read())

75
Close the file
After opening a file one should always close the opened file. We
use method close() for this.
Always make sure you explicitly close each open file, once its job is
done and you have no reason to keep it open. Because-There is an
upper limit to the number of files a program can open. If you exceed
that limit, there is no reliable way of recovery, so the program could
crash.
Each open file consumes some main-memory for the data-
structures associated with it, like file descriptor/handle or file locks
etc. So you could essentially end-up wasting lots of memory if you
have more files open that are not useful or usable.
Open files always stand a chance of corruption and data loss.

76
Example
f=open("test.txt")
#perform file operations
f.close()

Note:This method is not entirely safe. If an exception occurs when we


are performing some operation with the file, the code exits with out
closing the file. A safer way is to use a try...finally block.

77
seek and tell method
 We can change our current file cursor(position) using the
seek()method.
Similarly, the tell() method returns our current position(in number of
bytes).
Example

#filename=input("Enter your file name")


f=open("try.txt","r+w")
f.seek(6)
print(f.tell())
f.write("that")
print(f.read())
f.close()

78
Replace a word with another word
# Read in the file
with open('try.txt', 'r') as file :
filedata = file.read()
# Replace the target string
filedata = filedata.replace('that', 'somes')
# Write the file out again
with open('try.txt', 'w') as file:
file.write(filedata)

79
Attributes of File
There are following File attributes.
Once a file is opened following list of attributes can get information
related a file
Attribute Returns [Description]
Name Returns the name of the file
Mode Returns the mode in which file is being opened
Closed Returns Boolean Value. True, in case if file is closed else
false

80
#File Program on Attributes
result = open("data.txt", "w")
print ("Name of the file:",result.name )
print ("Opening mode:",result.mode )
print ("Closed or not:",result.closed)
result.close()
print ("Closed or not:",result.closed)

81
Modes of File
 There are different modes of file in which it can be opened. They are
mentioned in the following table
 A File can be opened in two modes:1.Text Mode2.Binary Mode
 The default is reading in text mode. In this mode, we get strings when
reading from the file.
On the other hand, binary mode returns bytes and this is the mode to
be used when dealing with non-text files like image or exe files.
Mode Description
R It opens in Reading mode. It is default mode of File. Pointer is at
beginning of the file.
w Open a file for writing. Creates a new file if it does not exist or
truncates the file if it exists
a Opens file in Appending mode. If file already exists, then append
the data at the end of existing file, else create a new file.
t Open in text mode(Default)

82
b Open in Binary mode
+ Open a file for updating(reading and writing)
rb It opens in Reading mode for binary format. It is the default
mode. Pointer is at beginning of file.
r+ Opens file for reading and writing. Pointer is at beginning of file.
rb+ Opens file for reading and writing in binary format. Pointer is at
beginning of file.
wb Opens file in Writing mode in binary format. If file already exists,
then overwrite the file else create a new file.
w+ Opens file for reading and writing. If file already exists, then
overwrite the file else create a new file.
wb+ Opens file for reading and writing in binary format. If file already
exists, then over write the file else create a new file.
ab Opens file in Appending mode in binary format. If file already
exists, then append the data at the end of existing file, else create a
new file.

83
a+ Opens file in reading and appending mode. If file already exists,
then append the data at the end of existing file, else create a new
file.
ab+ Opens file in reading and appending mode in binary format. If
file already exists, then append the data at the end of existing file, else
create a new file.
Note: Moreover, the default encoding is platform dependent. In
windows, it is'cp1252'but'utf-8'in Linux.
•So, we must not also rely on the default encoding or else our code will
behave differently in different platforms.
•Hence, when working with files in text mode, it is highly recommended
to specify the encoding type.f = open("test.txt",mode = 'r',encoding =
'utf-8')

84
Python File Methods
There are various methods available with the file object
Method Description
close() Close an open file. It has no effect if the file is already
closed.
detach() Separate the underlying binary buffer from the Text
IOBase and return it.
fileno() Return an integer number (file descriptor) of the file.flush()
Flush the write buffer of the file stream.
isatty() Return True if the file stream is interactive.
read(n) Read at most n characters form the file. Reads till end of
file if it is negative or None.
readable() Returns True if the file stream can be read from.

85
Method Description
readline(n=-1) Read and return one line from the file. Reads in at
most n bytes if specified.
readlines(n=-1) Read and return a list of lines from the file. Reads
in at most n bytes/characters if specified.
seek(offset,from=SEEK_SET) Change the file position to off set bytes, in
reference to from(start, current, end).
seekable() Returns True if the file stream supports random
access.
tell() Returns the current file location.
truncate(size=None) Resize the file stream to size bytes. If size is not
specified, resize to current location.
writable() Returns True if the file stream can be written to.
write(s) Write strings to the file and return the number of
characters written.
writelines(lines) Write a list of lines to the file.

86

You might also like