Unit 4 Cse
Unit 4 Cse
Unit 4 Cse
Python File Handling exists with the same name. The file
pointer exists at the beginning of the
Till now, we were taking the input from the console and
file.
writing it back to the console to interact with the user.
The file handling plays an important role when the data
6 wb It opens the file to write only in
needs to be stored permanently into the file. A file is a
binary format. It overwrites the file if
named location on disk to store related information. We can
it exists previously or creates a new
access the stored information (non-volatile) after the
one if no file exists. The file pointer
program termination.
exists at the beginning of the file.
The file-handling implementation is slightly lengthy or
complicated in the other programming language, but it is
7 w+ It opens the file to write and read
easier and shorter in Python.
both. It is different from r+ in the
In Python, files are treated in two modes as text or binary.
sense that it overwrites the previous
The file may be in the text or binary format, and each line of
file if one exists whereas r+ doesn't
a file is ended with the special character.
overwrite the previously written file.
Hence, a file operation can be done in the following order.
It creates a new file if no file exists.
o Open a file
The file pointer exists at the
o Read or write - Performing operation
beginning of the file.
o Close the file
p += 1
Common Exceptions
prime[0]= False Python provides the number of built-in exceptions, but here
we are describing the common standard exceptions. A list of
prime[1]= False common exceptions that can be thrown from a standard
Python program is given below.
# Print 1. ZeroDivisionError: Occurs when a number is
divided by zero.
for p in range(n + 1): 2. NameError: It occurs when a name is not found. It
may be local or global.
if prime[p]: 3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation
print (p,end=" ") fails.
5. EOFError: It occurs when the end of the file is
# main reached, and yet operations are being performed.
if __name__=='__main__':
n = 33
Exception handling in python
print ("The prime numbers smaller than or equal to", The try-expect statement
n,"is") If the Python program contains suspicious code that may
throw the exception, we must place that code in
SieveOfEratosthenes(n) the try block. The try block must be followed with
Output the except statement, which contains a block of code that
will be executed if there is some exception in the try block.
The prime numbers smaller than or equal to 33 is
2 3 5 7 11 13 17 19 23 29 31
Python Exception
An exception can be defined as an unusual condition in a
Syntax
program resulting in the interruption in the flow of the
1. try:
program.
2. #block of code
Whenever an exception occurs, the program stops the
3. except Exception1:
execution, and thus the further code is not executed.
4. #block of code
Therefore, an exception is the run-time errors that are unable
5. except Exception2:
to handle to Python script. An exception is a Python object
6. #block of code
that represents an error.
7. #other code
Python provides a way to handle the exception so that the
8. Consider the following example.
code can be executed without any interruption. If we do not
9. Example 1
handle the exception, the interpreter doesn't execute all the
10. try:
code that exists after the exception.
11. a = int(input("Enter a:"))
12. b = int(input("Enter b:"))
13. c = a/b
Assertions in Python
An assertion is a sanity-check that you can turn on or
turn off when you are done with your testing of the
program.
[By.- Prof. Narendra Kumar_CSE] Page 6
[Unit 4]
class Child(Parent): # define child class When the above code is executed, it produces the
def __init__(self): following result −
print "Calling child constructor" Calling child method
def childMethod(self):
print 'Calling child method'
c = Child() # instance of child Base Overloading Methods
c.childMethod() # child calls its method Following table lists some generic functionality that
c.parentMethod() # calls parent's method you can override in your own classes −
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method Sr.No. Method, Description & Sample Call
When the above code is executed, it produces the
1 __init__ ( self [,args...] )
following result −
Calling child constructor Constructor (with any optional arguments)
Calling child method Sample Call : obj = className(args)
Calling parent method
2 __del__( self )
Parent attribute : 200
Similar way, you can drive a class from multiple Destructor, deletes an object
parent classes as follows − Sample Call : del obj
class A: # define your class A
3 __repr__( self )
.....
class B: # define your class B Evaluable string representation
..... Sample Call : repr(obj)
class C(A, B): # subclass of A and B
..... 4 __str__( self )
You can use issubclass() or isinstance() functions to Printable string representation
check a relationships of two classes and instances. Sample Call : str(obj)
The issubclass(sub, sup) boolean function
5 __cmp__ ( self, x )
returns true if the given subclass sub is
indeed a subclass of the superclass sup. Object comparison
The isinstance(obj, Class) boolean function
Sample Call : cmp(obj, x)
returns true if obj is an instance of
class Class or is an instance of a subclass of
Class Overloading Operators
Suppose you have created a Vector class to
represent two-dimensional vectors, what happens
Overriding Methods when you use the plus operator to add them? Most
You can always override your parent class methods. likely Python will yell at you.
One reason for overriding parent's methods is You could, however, define the __add__ method in
because you may want special or different your class to perform vector addition and then the
functionality in your subclass. plus operator would behave as per expectation −
Example Example
#!/usr/bin/python #!/usr/bin/python
class Parent: # define parent class class Vector:
def myMethod(self): def __init__(self, a, b):
print 'Calling parent method' self.a = a
class Child(Parent): # define child class self.b = b
def myMethod(self): def __str__(self):
print 'Calling child method' return 'Vector (%d, %d)' % (self.a, self.b)
c = Child() # instance of child def __add__(self,other):
c.myMethod() # child calls overridden method return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
When the above code is executed, it produces the
following result −
Vector(7,8)
Data Hiding
An object's attributes may or may not be visible
outside the class definition. You need to name
attributes with a double underscore prefix, and
those attributes then are not be directly visible to
outsiders.
Example
#!/usr/bin/python
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print self.__secretCount
counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount
When the above code is executed, it produces the
following result −
1
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute
'__secretCount'
Python protects those members by internally
changing the name to include the class name. You
can access such attributes
as object._className__attrName. If you would
replace your last line as following, then it works for
you −
print counter._JustCounter__secretCount
When the above code is executed result −
1
2
2