II-MSC-PYTHON-UNIT-IV-NOTES
II-MSC-PYTHON-UNIT-IV-NOTES
CONTENTS
UNIT - 4
Python has been an object-oriented language since it existed. Because of this, creating and
using classes and objects are downright easy.
Class − 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.
Class variable − A variable that is shared by all instances of a class. Class variables are
defined within a class but outside any of the class's methods. Class variables are not used
as frequently as instance variables are.
Data member − A class variable or instance variable that holds data associated with a
class and its objects.
Instance variable − A variable that is defined inside a method and belongs only to the
current instance of a class.
Inheritance −The transfer of the characteristics of a class to other classes that arederived
from it.
Instance − An individual object of a certain class. An object obj that belongs to a class
Circle, for example, is an instance of the class Circle.
Object − A unique instance of a data structure that's defined by its class. An object
comprises both data members (class variables and instance variables) and methods.
The class statement creates a new class definition. The name of the class immediately
follows the keyword class followed by a colon as follows −
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.
Example
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
The variable empCount is a class variable whose value is shared among all instances of a
this class. This can be accessed as Employee.empCount from inside the class or outside
the class.
The first method init () is a special method, which is called class constructor or
initialization method that Python calls when you create a new instance of this class.
You declare other class methods like normal functions with the exception that the first
argument to each method is self. Python adds the self argument to the list for you; you do
not need to include it when you call the methods.
To create instances of a class, you call the class using class name and pass in whatever
arguments its init method accepts.
You access the object's attributes using the dot operator with object.
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
3 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI
DCS33-PROGRAMMING USING PYTHON UNIT IV
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
You can add, remove, or modify attributes of classes and objects at any time −
Instead of using the normal statements to access attributes, you can use the following functions
4 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI
DCS33-PROGRAMMING USING PYTHON UNIT IV
Every Python class keeps following built-in attributes and they can be accessed using
dot operator like any other attribute −
bases − A possibly empty tuple containing the base classes, in the order of
their occurrence in the base class list.
For the above class let us try to access all these attributes −
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
Python deletes unneeded objects (built-in types or class instances) automatically to free
the memory space.
The process by which Python periodically reclaims blocks of memory that no longer are
in use is termed Garbage Collection.
Python's garbage collector runs during program execution and is triggered when anobject's
reference count reaches zero. An object's reference count changes as the number of aliases
that point to it changes.
The object's reference count decreases when it's deleted with del, its reference is reassigned,
or its reference goes out of scope. When an object's reference count reaches zero, Python
collects it automatically.
when the garbage collector destroys an orphaned instance and reclaims its space. But a
class can implement the special method del (), called a destructor, that is invoked when
the instance is about to be destroyed.
This method might be used to clean up any non memory resources used by an instance.
Example
This __del__() destructor prints the class name of an instance that is about to be destroyed −
#!/usr/bin/python
class Point:
def init ( self, x=0, y=0):
self.x = x
self.y = y
def del (self):
class_name = self. class . name
print class_name, "destroyed"
pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3
Create a class by deriving it from a preexisting class by listing the parent class in
parentheses after the new class name.
The child class inherits the attributes of its parent class, and you can use those attributes
as if they were defined in the child class.
A child class can also override data members and methods from the parent.
Syntax
Derived classes are declared much like their parent class; however, a list of base classes
to inherit from is given after the class name −
Example
#!/usr/bin/python
def parentMethod(self):
print 'Calling parent method'
def getAttr(self):
print "Parent attribute :", Parent.parentAttr
def childMethod(self):
Similar way, you can drive a class from multiple parent classes as follows −
You can use issubclass() or isinstance() functions to check a relationships of two classes and
instances.
The issubclass(sub, sup) boolean function returns true if the given subclass sub is
indeed a subclass of the superclass sup.
Override your parent class methods. One reason for overriding parent's methods is
because you may want special or different functionality in your subclass.
Example
#!/usr/bin/python
Following table lists some generic functionality that you can override in your own classes −
1
init ( self [,args...] )
2
del ( self )
3
repr ( self )
4
str ( self )
5
cmp ( self, x )
Object comparison
It define the add method in your class to perform vector addition and then the plus
operator would behave as per expectation –
Example
#!/usr/bin/python
class Vector:
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
Vector(7,8)
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
1
2
4.7 Exception handling
Python provides two very important features to handle any unexpected error in your
Python programs and to add debugging capabilities in them.
Exception Handling − This would be covered in this tutorial. Here is a list standard
Exceptions available in Python: Standard Exceptions.
2 Stop Iteration-Raised when the next() method of an iterator does not point to any object.
4
Standard Error-Base class for all built-in exceptions except StopIteration and
SystemExit.
5 Arithmetic Error- Base class for all errors that occur for numeric calculation.
6
Overflow Error
8 Zero Division Error- Raised when division or modulo by zero takes place for all numeric
types.
11
EOF Error-Raised when there is no input from either the raw_input() or input() function
and the end of file is reached.
16 Key Error-Raised when the specified key is not found in the dictionary.
17 Name Error-Raised when an identifier is not found in the local or global namespace.
18
Unbound Local Error-Raised when trying to access a local variable in a function or
method but no value has been assigned to it.
19 Environment Error-Base class for all exceptions that occur outside the Python
environment.
20 IO Error-Raised when an input/ output operation fails, such as the print statement or the
open() function when trying to open a file that does not exist.
24 System Error- Raised when the interpreter finds an internal problem, but when this error
is encountered the Python interpreter does not exit.
25 System Exit- Raised when Python interpreter is quit by using the sys.exit() function. If not
handled in the code, causes the interpreter to exit.
26
Type Error-Raised when an operation or function is attempted that is invalid for the
specified data type.
27 Value Error-Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified.
28 Runtime Error-Raised when a generated error does not fall into any category.
29
Not Implemented Error- Raised when an abstract method that needs to be implemented
in an inherited class is not actually implemented.
4.7.1 Exception
An exception is an event, which occurs during the execution of a program that disrupts
the normal flow of the program's instructions.
In general, when a Python script encounters a situation that it cannot cope with, it raises
an exception. An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.
If you have some suspicious code that may raise an exception, you can defend your
program by placing the suspicious code in a try: block.
After the try: block, include an except: statement, followed by a block of code which
handles the problem as elegantly as possible.
Syntax
Example
This example opens a file, writes content in the, file and comes out gracefully because there is
no problem at all −
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()
This produces the following result − Written content in the file successfully
Example
This example tries to open a file where you do not have write permission, so it raises an
exception −
#!/usr/bin/python
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
This produces the following result − Error: can't find file or read data
You can also use the except statement with no exceptions defined as follows −
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
This kind of a try-except statement catches all the exceptions that occur. Using this kind
of try-except statement is not considered a good programming practice though, because
it catches all exceptions but does not make the programmer identify the root cause of the
problem that may occur.
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
The finally block is a place to put any code that must execute, whether the try-block
raised an exception or not. The syntax of the try-finally statement is this −
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
You cannot use else clause as well along with a finally clause.
Example
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"
If you do not have permission to open the file in writing mode, then this will produce the
following result −Error: can't find file or read data
#!/usr/bin/python
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"
When an exception is thrown in the try block, the execution immediately passes tothe
finally block.
After all the statements in the finally block are executed, the exception is raised again and
is handled in the except statements if present in the next higher layer of the try- except
statement.
An exception can have an argument, which is a value that gives additional information
about the problem. The contents of the argument vary by exception.
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable follow the
name of the exception in the except statement.
If you are trapping multiple exceptions, you can have a variable follow the tuple of the
exception.
This variable receives the value of the exception mostly containing the cause of the
exception.
The variable can receive a single value or multiple values in the form of a tuple. This
tuple usually contains the error string, the error number, and an error location.
Example
#!/usr/bin/python
This produces the following result − The argument does not contain numbers
You can raise exceptions in several ways by using the raise statement.
Syntax
raise [Exception [, args [, traceback]]]
Here, Exception is the type of exception (for example, NameError) and argument is a
value for the exception argument. The argument is optional; if not supplied, the exception
argument is None.
The final argument, traceback, is also optional (and rarely used in practice), and if present,
is the traceback object used for the exception.
Example
An exception can be a string, a class or an object. Most of the exceptions that the Python
core raises are classes, with an argument that is an instance of the class.
Python also allows you to create your own exceptions by deriving classes from the
standard built-in exceptions.
In the try block, the user-defined exception is raised and caught in the except block. The
variable e is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def init (self, arg):
self.args = arg
So once you defined above class, you can raise the exception as follows −
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
An assertion is a sanity-check that you can turn on or turn off when you are done with
your testing of the program.
The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more
accurate, a raise-if-not statement). An expression is tested, and if the result comes up false,
an exception is raised.
Assertions are carried out by the assert statement, the newest keyword to Python,
introduced in version 1.5.
Programmers often place assertions at the start of a function to check for valid input, and
after a function call to check for valid output.
If the assertion fails, Python uses ArgumentExpression as the argument for the
AssertionError. AssertionError exceptions can be caught and handled like any other
exception using the try-except statement, but if not handled, they will terminate the
program and produce a traceback.
Example
Here is a function that converts a temperature from degrees Kelvin to degrees Fahrenheit.
Since zero degrees Kelvin is as cold as it gets, the function bails out if it sees a negative
temperature −
#!/usr/bin/python
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
When the above code is executed, it produces the following result −32.0
451
Traceback (most recent call last):
File "test.py", line 9, in <module>
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!
PART-A QUESTIONS
PART-B QUESTIONS
1. What is inheritance? Illustrate types of inheritance with python code.
2. Compare class and object with python code.
3. Compare method overloading and overriding.
4. Describe in detail printing to the screen.
5. Explain with example the need for exceptions.
6. Explain built in exceptions.
7. Difference between built in exceptions and handling exception.
8. How do we implement abstract method in python? Give an example for the same.
PART-C QUESTIONS
1. Explain Object-Oriented Programming methodologies in detail
2. What is an Exception? Explain types of exceptions and give an example.
3. How to create user defined exception in python with an example.
4. Difference between Raising and User defined exceptions in python?
5. Write a syntax for Handling Exceptions with example
i)try
ii) try-except
iii) try-except-else
iv) try-except-else-finally