0% found this document useful (0 votes)
2 views28 pages

II-MSC-PYTHON-UNIT-IV-NOTES

The document outlines the contents of Unit 4 of a Python programming course, focusing on object-oriented programming concepts such as classes, inheritance, and exception handling. It covers topics including creating classes, accessing attributes, garbage collection, and method overriding, providing examples and explanations for each concept. Additionally, it discusses built-in class attributes and the use of assertions in Python.

Uploaded by

RCW CS 18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views28 pages

II-MSC-PYTHON-UNIT-IV-NOTES

The document outlines the contents of Unit 4 of a Python programming course, focusing on object-oriented programming concepts such as classes, inheritance, and exception handling. It covers topics including creating classes, accessing attributes, garbage collection, and method overriding, providing examples and explanations for each concept. Additionally, it discusses built-in class attributes and the use of assertions in Python.

Uploaded by

RCW CS 18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

DCS33– PROGRAMMING USING PYTHON

CONTENTS
UNIT - 4

Chapter Topic’s Page No


4.1 Object oriented 1
4.1.1 Overview of OOP Terminology 1
4.1.2 Creating Classes 2
4.1.3 Creating Instance Objects 3
4.1.4 Accessing Attributes 3
4.2 Built-In Class Attributes 5
4.3 Destroying Objects (Garbage Collection) 7
4.4 Class Inheritance 8
4.5 Overriding Methods 11
4.5.1 Base Overloading Method 11
4.5.2 Overloading Operators 12
4.6 Data Hiding 13
4.7 Exception handling 14
4.7.1 Exception 17
4.7.2 Handling an exception 17
4.7.3 The try-finally Clause 20
4.7.4 Argument of an Exception 21
4.7.5 Raising an Exceptions 22
4.7.6 User-Defined Exceptions 23
4.8 Assertions in Python 24
4.8.1 The assert Statement 24
DCS33-PROGRAMMING USING PYTHON UNIT IV

4.1 Object oriented

 Python has been an object-oriented language since it existed. Because of this, creating and
using classes and objects are downright easy.

4.1.1 Overview of OOP Terminology

 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.

 Function overloading − The assignment of more than one behavior to a particular


function. The operation performed varies by the types of objects or arguments involved.

 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.

 Instantiation − The creation of an instance of a class.

 Method − A special kind of function that is defined in a class definition.

 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.

1 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

 Operator overloading − The assignment of more than one function to a particular


operator.

4.1.2 Creating Classes

 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

Following is the example of a simple Python class

class Employee:
'Common base class for all employees'
empCount = 0

def init (self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print "Total Employee %d" % Employee.empCount

def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary

2 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

 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.

4.1.3 Creating Instance Objects

 To create instances of a class, you call the class using class name and pass in whatever
arguments its init method accepts.

"This would create first object of Employee class"


emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)

4.1.4 Accessing Attributes

 You access the object's attributes using the dot operator with object.

 Class variable would be accessed using class name as follows −

emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

Now, putting all the concepts together −

#!/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 init (self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print "Total Employee %d" % Employee.empCount

def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary

"This would create first object of Employee class"


emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

When the above code is executed, it produces the following result −

Name : Zara ,Salary: 2000


Name : Manni ,Salary: 5000
Total Employee 2

You can add, remove, or modify attributes of classes and objects at any time −

emp1.age = 7 # Add an 'age' attribute.


emp1.age = 8 # Modify 'age' attribute.
del emp1.age # Delete 'age' attribute.

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

 The getattr(obj, name[, default]) − to access the attribute of object.

 The hasattr(obj,name) − to check if an attribute exists or not.

 The setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it


would be created.

 The delattr(obj, name) − to delete an attribute.

hasattr(emp1, 'age') # Returns true if 'age' attribute exists


getattr(emp1, 'age') # Returns value of 'age' attribute
setattr(emp1, 'age', 8) # Set attribute 'age' at 8
delattr(empl, 'age') # Delete attribute 'age'

4.2 Built-In Class Attributes

 Every Python class keeps following built-in attributes and they can be accessed using
dot operator like any other attribute −

 dict − Dictionary containing the class's namespace.

 doc − Class documentation string or none, if undefined.

 name − Class name.

 module − Module name in which the class is defined. This attribute is


" main " in interactive mode.

 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

5 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

def init (self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print "Total Employee %d" % Employee.empCount

def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary

print "Employee. doc__:", Employee. doc


print "Employee. name :", Employee. name__
print "Employee. module :", Employee. module
print "Employee. bases :", Employee. bases__
print "Employee. dict__:", Employee. dict

When the above code is executed, it produces the following result −

Employee. doc : Common base class for all employees


Employee. name : Employee
Employee. module : main
Employee. bases : ()
Employee. dict : {' module ': ' main ', 'displayCount':
<function displayCount at 0xb7c84994>, 'empCount': 2,
'displayEmployee': <function displayEmployee at 0xb7c8441c>,
' doc ': 'Common base class for all employees',
' init ': <function init at 0xb7c846bc>}

6 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

4.3 Destroying Objects (Garbage Collection)

 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.

 An object's reference count increases when it is assigned a new name or placed in a


container (list, tuple, or dictionary).

 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.

a = 40 # Create object <40>


b=a # Increase ref. count of <40>
c = [b] # Increase ref. count of <40>

del a # Decrease ref. count of <40>


b = 100 # Decrease ref. count of <40>
c[0] = -1 # Decrease ref. count of <40>

 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.

7 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

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

When the above code is executed, it produces following result −

3083401324 3083401324 3083401324

4.4 Class Inheritance

 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.

8 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

 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 −

class SubClassName (ParentClass1[, ParentClass2, ...]):


'Optional class documentation string'
class_suite

Example
#!/usr/bin/python

class Parent: # define parent class


parentAttr = 100
def init (self):
print "Calling parent constructor"

def parentMethod(self):
print 'Calling parent method'

def setAttr(self, attr):


Parent.parentAttr = attr

def getAttr(self):
print "Parent attribute :", Parent.parentAttr

class Child(Parent): # define child class


def init (self):
print "Calling child constructor"

def childMethod(self):

9 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

print 'Calling child method'

c = Child() # instance of child


c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method

When the above code is executed, it produces the following result −

Calling child constructor


Calling child method
Calling parent method
Parent attribute : 200

Similar way, you can drive a class from multiple parent classes as follows −

class A: # define your class A


.....
class B: # define your class B
.....
class C(A, B): # subclass of A and B
.....

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.

 The isinstance(obj, Class) boolean function returns true if obj is an instance of


class Class or is an instance of a subclass of Class.

10 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

4.5 Overriding Methods

 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

class Parent: # define parent class


def myMethod(self):
print 'Calling parent method'

class Child(Parent): # define child class


def myMethod(self):
print 'Calling child method'

c = Child() # instance of child


c.myMethod() # child calls overridden method

When the above code is executed, it produces the following result −

Calling child method

4.5.1 Base Overloading Methods

Following table lists some generic functionality that you can override in your own classes −

S.No. Method, Description & Sample Call

1
init ( self [,args...] )

Constructor (with any optional arguments)

11 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

Sample Call : obj = className(args)

2
del ( self )

Destructor, deletes an object

Sample Call : del obj

3
repr ( self )

Evaluable string representation

Sample Call : repr(obj)

4
str ( self )

Printable string representation

Sample Call : str(obj)

5
cmp ( self, x )

Object comparison

Sample Call : cmp(obj, x)

4.5.2 Overloading Operators

 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:

12 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

def init (self, a, b):


self.a = a
self.b = b

def str (self):


return 'Vector (%d, %d)' % (self.a, self.b)

def add (self,other):


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)

4.6 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

13 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

counter = JustCounter()
counter.count()
counter.count()
print counter. secretCount

When the above code is executed, it produces the following result –

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.

List of Standard Exceptions

S.No. Exception Name & Description

1 Exception-Base class for all exceptions

2 Stop Iteration-Raised when the next() method of an iterator does not point to any object.

3 System Exit-Raised by the sys.exit() function.

4
Standard Error-Base class for all built-in exceptions except StopIteration and
SystemExit.

14 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

5 Arithmetic Error- Base class for all errors that occur for numeric calculation.

6
Overflow Error

Raised when a calculation exceeds maximum limit for a numeric type.

7 Floating Point Error-Raised when a floating point calculation fails.

8 Zero Division Error- Raised when division or modulo by zero takes place for all numeric
types.

9 Assertion Error-Raised in case of failure of the Assert statement.

10 Attribute Error-Raised in case of failure of attribute reference or assignment.

11
EOF Error-Raised when there is no input from either the raw_input() or input() function
and the end of file is reached.

12 Import Error-Raised when an import statement fails.

13 Keyboard Interrupt-Raised when the user interrupts program execution, usually by


pressing Ctrl+c.

14 Lookup Error-Base class for all lookup errors.

15 Index Error-Raised when an index is not found in a sequence.

15 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

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.

21 IO Error -Raised for operating system-related errors.

22 Syntax Error-Raised when there is an error in Python syntax.

23 Indentation Error-Raised when indentation is not specified properly.

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.

16 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

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.

4.7.2 Handling an exception

 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

Here is simple syntax of try....except...else blocks − try:

You do your operations here;


......................
except ExceptionI:

17 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

If there is ExceptionI, then execute this block.


except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.

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:

18 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

print "Error: can\'t find file or read data"


else:
print "Written content in the file successfully"

This produces the following result − Error: can't find file or read data

The except Clause with No Exceptions

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:

If there is no exception then execute this block.

 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.

The except Clause with Multiple Exceptions

except statement to handle multiple exceptions as follows −

try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.

19 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

......................
else:
If there is no exception then execute this block.

4.7.3 The try-finally Clause

 You can use a finally: block along with a try: 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

DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


20
DCS33-PROGRAMMING USING PYTHON UNIT IV

Same example can be written more cleanly as follows −

#!/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.

4.7.4 Argument of an Exception

 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.

 You capture an exception's argument by supplying a variable in the except clause as


follows −

try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...

DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


21
DCS33-PROGRAMMING USING PYTHON UNIT IV

 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

Following is an example for a single exception −

#!/usr/bin/python

# Define a function here.


def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers\n", Argument

# Call above function here.


temp_convert("xyz");

This produces the following result − The argument does not contain numbers

invalid literal for int() with base 10: 'xyz'

4.7.5 Raising an Exceptions

 You can raise exceptions in several ways by using the raise statement.

 The general syntax for the raise statement is as follows.

22 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

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.

 Defining new exceptions is quite easy and can be done as follows −

def functionName( level ):


if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception

4.7.6 User-Defined Exceptions

 Python also allows you to create your own exceptions by deriving classes from the
standard built-in exceptions.

 Here is an example related to RuntimeError. Here, a class is created that is subclassed


from RuntimeError. This is useful when you need to display more specific information
when an exception is caught.

 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.

23 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

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

4.8 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.

 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.

4.8.1 The assert Statement

 When it encounters an assert statement, Python evaluates the accompanying expression,


which is hopefully true.

 If the expression is false, Python raises an AssertionError exception.

The syntax for assert is − assert Expression[, Arguments]

 If the assertion fails, Python uses ArgumentExpression as the argument for the
AssertionError. AssertionError exceptions can be caught and handled like any other

24 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

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!

DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


25
DCS33-PROGRAMMING USING PYTHON UNIT IV

OBJECT ORIENTED PROGRAMMING

Syllabus: [Regulation: 2021]


UNIT - IV: Class Definition - Creating Objects - Built-in Attribute Methods - Built-in Class
Attributes - Destructors in Python Encapsulation - Data Hiding- Inheritance - Method Overriding
Polymorphism. Exception Handling: Built-in Exceptions - Handling Exceptions – Exception with
Arguments- Raising Exception - User-defined Exception - Assertions in Python

PART-A QUESTIONS

1. What is Object-Oriented Programming?


2. Difference between Object-Oriented and Procedural Oriented Programming.
3. What are Classes and Objects?
4. Define encapsulation.
5. Define data hiding.
6. List some of its advantages of OOP.
7. Define binding.
8. Differentiate between static and dynamic binding.
9. Differentiate Constructor and Destructors.

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.

1 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT IV

9. Explain Function overloading with an example.


10. What is inheritance? Explain with an example.

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

2 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI

You might also like