Unit III File Handling , Classes
Unit III File Handling , Classes
example2
f=open("D:/test.txt","r")
print(f.read(5))
---------
output:
hello
append()-example
#append example
f=open("D:/test.txt","a")
print(f.write("this is a appending operation in file"))
-------------------------
output:
37
example
Counts number of lines and print them.
f=open("D:/test.txt","r")
for x in f:
print (x)
_______
output:
hello everyone, welcome to python programming classes
this is a appending operation in file
access modes:read
r-read: only reading
file must exsits before opening file
file pointer points at the begining of the file.
write mode
w-writing contents into the file
file exists-begining of file and over writtens the data
not exists-new files is created
append()
file exists :pointer points at the end of the content.
new file is created
writing to the file
write()- single line
writelines()-multi line
example:
#reading file and display the contents
f=open("D:/test.txt","r")
print(f.read())
_____________
output:
hello everyone, welcome to python programming classes
example:
f=open("D:/test.txt","w")
print(f.write("this is a appending operation in file"))
--------------
output:
37
contin
f=open("D:/test.txt","r")
for x in f:
print (x)
--------------------
output:
this is a appending operation in file
delete()
first close the opened file.
f.close()
import library os
syntax:
os.remove(“path of file”)
Delete()
#example
f=open("D:/test.txt","r")
for x in f:
print (x)
-----------------------
output:
this is a appending operation in file
conti...
#delete a file
import os
os.remove("D:/test.txt")
various access modes
Mode purpose
r default mode
rb binary format
a appending
ab binary format
functions
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Class
data
functions
student
roll_no
name
write
read
syntax:
object.name=class_name()
Class class Student:
Student_RollNo=10
Student_Name=“John”
data
functions
student
roll_no
name
write
read
functions
syntax:
object.name=class_name()
class Dog:
# A simple class
# attribute
attr1 = "mammal"
attr2 = "dog"
# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)
# Driver code
# Object instantiation
Rodger = Dog()
def print_emp_info(emplist):
print(f’Emp Name is “{emplist.name}”)
print(f”Designation is “{emplist.designation}”)
e1 = Emp(“John”,”Manager”)
print_emp_info(e1)
class Track:
def __init__(self, song, art):
self.song=song
self.art=art
def print_track_info(vocalist):
print(f”Song is “{vocalist.song}”)
print(f”Artist is “{vocalist.art}”)
singer = Track(“Song name”,”Robert”)
print_track_info(singer)
Object as Return Values:
class Circle:
def __init__(self,radius):
self.radius=radius
self.status=""
def check_point_status(self):
if self.radius<30:
self.status="Green"
return self def main():
point = Circle(10)
obj=point.check_point_status()
print(obj.status)
print(isinstance(point,Circle))
print(isinstance(obj,Circle))
print(id(point))
print(id(obj))
if __name__ == "__main__":
main()
Class Attributes & Data Attributes
Encapsulation
Using Private Instance Variables
Inheritance
Accessing Inherited Variables & Methods
Use of super()
Polymorphism
Operator Overloading & Magic Methods
Encapsulation
In Python, encapsulation refers to the bundling of data
(attributes) and methods (functions) that operate on
the data into a single unit
Encapsulation features :
Organized variable and its methods.
Avoids unnecessary modification of variable.
Can use across the modular programming.
Example
class Public:
def __init__(self ):
self.name = "John" # Public attribute
def display_name(self):
print(self.name) # Public method
obj = Public()
obj.display_name() # Accessible
print(obj.name) # Accessible
Polymorphism
Polymorphism means that you can have multiple
classes where each class implements the same
variables or methods in different ways. Polymorphism
takes advantages of inheritance in order to make this
happen.
Example:
def add(a, b):
return a + b
print(add(3, 4)) # Integer addition
print(add("Hello, ", "World!")) # String concatenation
print(add([1, 2], [3, 4])) # List concatenation
Example 2:
class Shape: class Circle(Shape):
def area(self): def __init__(self, radius):
return "Undefined" self.radius = radius
def area(self):
class Rectangle(Shape): return 3.14 * self.radius ** 2
def __init__(self, length, width):
self.length = length shapes = [Rectangle(2, 3),
self.width = width Circle(5)]
def area(self): for shape in shapes:
return self.length * self.width print(f"Area: {shape.area()}")
Operator Overloading
Normally operators like +,-,/,*, works fine with built-in datatypes.
Changing the behavior of an operator so that it works with programmer
defined types(class) is called operator overloading.
Basic operators like +, -, * etc. can be overloaded. To overload an operator, one
needs to write a method within user-defined class. The method should consist
of the code what the programmer is willing to do with the operator.
Let us consider an example to overload + operator to add two Time
objects by defining add method inside the class.
In the above example,
when the statement t3=t1+t2 is used, it invokes a special method add ()
written inside the class. Because, internal meaning of this statement is t3 = t1.
add (t2)
Here, t1 is the object invoking the method. Hence, self inside add () is the
reference (alias) of t1. And, t2 is passed as argument explicitly.
Python provides a special set of methods which have to be used for overloading
operator. Following table shows gives a list of operators and their respective
Python methods for overloading.
Exception Handling
Using try… except… finally
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The else block lets you execute code when there is no
error.
The finally block lets you execute code, regardless of the
result of the try- and except blocks.
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Types of Errors in Python
Syntax errors:
Syntax errors occur when the code violates the rules of the Python
language syntax. These errors are detected by the Python interpreter
when it is parsing the code. (Missing colon, Unmatched
parentheses, Missing quotes, Using a keyword as a variable name,
Missing indentation)
Runtime errors:
Runtime errors occur when the code is syntactically correct but causes
an error when it is executed. These errors can be caused by a variety of
reasons, such as invalid input data, division by zero, or accessing an
undefined variable.
Logical errors:
Logical errors occur when the code is syntactically correct and runs
without causing any errors, but the output is not what you expected.
These errors can be caused by incorrect algorithmic design,
mathematical errors, or a misunderstanding of the problem
requirements.
Examples
if x>0
print(“x is positive”) x=”20”
y=10
********************** z=x/y #TypeError
list1=[10,20,30]
print(list1[4]) ***********************
#IndexError
str1=”Hello, Sam”
*********************** str1.reverse() #AttributeError
a=5
b=10 ************************
average = a+b /2 x=0
print(average) while x<20:
print(x)
*******************
a=20
print(b) # Name Error
Build-in exceptions in python
1) SyntaxError: Raised when there is a syntax error in the Python code
2) Type Error: Raised when an operation or function is applied to an object of
inappropriate type.
3) ValueError: Raised when a built-in operation or function receives an argument
that has the right type but an inappropriate value.
4) IndexError: Raised when trying to access an index that does not exist in a
sequence.
5) KeyError: Raised when trying to access a key that does not exist in a dictionary.
6) NameError: Raised when a variable name is not defined.
7) AttributeError: Raised when trying to access an attribute that does not exist.
8) I/OError: Raised when an input/output operation fails.
9) ZeroDivisionError: Raised when trying to divide a number by zero.
10) MemoryError: Creating a large list or array that exceeds the available memory
11) ImportError: Raised when an import statement fails to find and load the
requested module.
Program to check for ValueError Exception
while True:
try:
number = int(input("Enter a number:"))
print(f"The number you have entered is {number}")
break
except ValueError:
print("Oops! That was no valid number. Try again...")
Output:
Enter a number: wer
Oops! That was no valid number. Try again...
Enter a number:4.0
Oops! That was no valid number. Try again...
Enter a number:
Program to check for ZeroDivisionError
x=int(input("Enter value of x:")) Output:
y=int(input("Enter value of y:")) Enter value of x:4
try: Enter value of y:2
result=x/y Result is 2.0
except ZeroDivisionError: Executing finally clause
print("Division by zero")
else: Enter value of x:2
print(f"Result is {result}") Enter value of y:0
finally: Division by zero
print("Executing finally Executing finally clause
clause")
Encapsulation
In Python, encapsulation refers to the bundling of data
(attributes) and methods (functions) that operate on
the data into a single unit
Encapsulation features :
Organized variable and its methods.
Avoids unnecessary modification of variable.
Can use across the modular programming.
Encapsulation in python
Wrapping of variables and functions under a single unit
data hiding, private
Ex: Class Encap:
Class Encap: __a=10
a=10 def display(self):
def display(self):
print(self.a) print(self.__a)
e=Encap() e=Encap()
e.display() e.display()
print(e.a) print(e.a)
# Invalid cannot access private var
Python provides _ _
__a =10 is represented as private variable
__display(self): is represented as private method
Class Encap:
__a=10
def __display(self ):
print(self.__a)
def show(self):
self.__display()
e=Encap()
e.display() # Invalid cannot access private var
print(e.a) # Invalid cannot access private var
e.show()
Class Encap:
__a=10
def setA(self,a):
self.a=a
def getA(self):
return(self.a)
e=Encap()
e.setA(30)
print(e.getA())
Consider I have 2 forms :
Student register form
Student login form
def setNAME(self,name):
self.__name=name Event: Btn_Save()
def getNAME(self):
return(self.__name)
def setAGE(self,age): objStudent= StudentEncap()
self.__age=age objStudent.setName(txtName.text())
def getAGE(self): objStudent.setAge(txtAge.text())
return(self.__age)
def setUSERNAME(self,username): InsertToDatabase(objStudent)
self.__username=username
********************************************
def getUSERNAME(self):
return(self.__username) Event: Btn_View()
def setPASSWORD(self,password):
self.__password=password objStudent = StudentEncap()
def getPASSWORD(self):
return(self.__password) objStudent=GetDetailsFromDatabase()
txtName.text=s1.getName()
txtAge.text=s1.getAge()
Variables & Methods in python
Instance variables
Static variables // Class level var : Value is same for all
objects
Local variables
class Student:
def __init__(self,rno,name):
self.rno=rno
S1=Student(72,”John”)
self.name=name S1.display()
Student.uni=“MLR” S2.Student(73,”Smith”)
def display(self):
print(self.ro,self.name)
S2.display()
class Student:
uni=“Mlore”
def __init__(self,rno,name): @staticmethod
self.rno=rno def show(): No self paramtere
self.name=name Student.uni=“MLOR”
def display(self): print(Student.uni)
print(self.ro,self.name)
print(Student.uni) S1=Student(72,”John”)
S1.display()
S2.Student(73,”Smith”)
S2.display()
Student.show()
# program to illustrate access modifiers of a class # public member function
def displayPublicMembers(self):
# super class
# accessing public data members
class Super:
print("Public Data Member:", self.var1)
class AbstractDemo2(AbstractDemo1):
def display(Self):
print(“AD@ display”)
Obj=AbsractDemo2()
Obj.display()
from abc import ABC, abstractmethod
Class AbstractDemo1(ABC): #abstract class
@abstractmethod #decorator
def display(self):
pass
@abstractmethod #decorator
def show(self):
pass
class AbstractDemo2(AbstractDemo1): #abstract class Its not having all methods of abstract class
def display(Self):
print(“AD2 display”)
class AbstractDemo3(AbstractDemo1):
def display(Self):
print(“AD3 display”)
def Show(Self):
print(“AD3 display”)
Obj=AbsractDemo3()
Obj.display()
Obj.show()
Polymorphism:
Operator Overloading:
Using same operator for different purpose
We can provide extra meaning to existing operator
without changing its previous meaning
+ add 2 numbers; concatenate 2 strings;
cannot add 2 objects, but can be done using operator
overloading
Method Overloading
Method Overriding
Method Overloading class Number:
class Number: def __init__(Self,a,b,c):
def __init__(Self,a,b,c): Self.a=a
Self.b=b
Self.a=a Self.c=c
Self.b=b #Predefined syntax
Self.c=c def __add__(Self,other):
N1=Number(1,2,3) a=Self.a+other.a
b=Self.b+other.b
N2=Number(4,5,6) c=Self.c+other.c
res=Number(a,b,c)
N1+N2 (5,7,9) return res
def __lt__(Self,other):
o1=self.a+self.b+self.c
o2=other.a+other.b+other.c
if(o1<o2):
return True
else:
N1=Number(1,2,3) return False
N2=Number(4,5,6)
class Base:
def display(Self):
print(“Base Class display”)
class Derived(Base): #if it is not satisfied base class methods definition