Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER
UNIT VI
Classes and OOP
6.1. Classes
Python is an object oriented programming language. Unlike procedure oriented
programming, where the main emphasis is on functions, object oriented programming stress on
objects. Object is simply a collection of data (variables) and methods (functions) that act on
those data. And, class is a blueprint for the object. We can think of class as a sketch (prototype)
of a house. It contains all the details about the floors, doors, windows etc. Based on these
descriptions we build the house. House is the object. As, many houses can be made from a
description, we can create many objects from a class. An object is also called an instance of a
class and the process of creating this object is called instantiation.
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 are derived 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.
1
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER
class MyNewClass:
'''This is a docstring. I have created a new class'''
Pass
6.2. Objects
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.
It can also be used to create new object instances (instantiation) of that class. The
procedure to create an object is similar to a function call.
We can access attributes of objects using the object name prefix.
Attributes may be data or method. Method of an object are corresponding functions of that
class. Any function object that is a class attribute defines a method for objects of that
class.
You can define the following class with the name Snake. This class will have an attribute name.
You can assign the class to a variable. This is called object instantiation. You will then be able to
access the attributes that are present inside the class using the dot . operator. For example, in the
Snake example, you can access the attribute name of the class Snake.
2
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER
>>> # access the class attribute name inside the class Snake.
>>> print(snake.name)
python
Methods
Once there are attributes that “belong” to the class, you can define functions that will access the
class attribute. These functions are called methods. When you define methods, you will need to
always provide the first argument to the method with a self keyword.
For example, you can define a class Snake, which has one attribute name and one method
change_name. The method change name will take in an argument new_name along with the
keyword self.
Now, you can instantiate this class Snake with a variable snake and then change the name with
the method change_name.
3
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER
You can also provide the values for the attributes at runtime. This is done by defining the
attributes inside the init method. The following example illustrates this.
class Snake:
Now you can directly define separate attribute values for separate objects. For example,
4
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER
python
>>> print(anaconda.name)
anaconda
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
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)
5
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER
Instead of using the normal statements to access attributes, you can use the following functions −
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.
Attributes:
name: A string representing the customer's name.
balance: A float tracking the current balance of the customer's account.
"""
6
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER
self.name = name
How is a model different from a Python dictionary then? Easy. Dictionaries know nothing about
where the data came from, what parts of it are important for us, how the values should be
converted to and fro, and how should the data be validated before it is stored somewhere. A
model of an apple does know what properties should an object have to be a Proper Apple; what
can be done the apple so that it does not stop being a Proper Apple; and where does the apple
belong so it won’t be in the way when it isn’t needed anymore.
7
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER
In other words, the model is an answer to questions what, where and how about a document. And
a dictionary is a document (or, more precisely, a simple representation of the document in given
environment).
The simplest possible model:
class Thing(Model):
pass
Just a Python class. Not very useful as it does not specify any property. Let’s observe the object
thoroughly and conclude that colour is an important distinctive feature of this... um, sort of thing:
class Thing(Model):
colour = Property()
Great, now that’s a model. It recognizes a property as significant. Now we can compare, search
and distinguish objects by colour (and its presence or lack). Obviously, if colour is an applicable
property for an object, then it belongs to this model.
import shelve
s = shelve.open('test_shelf.db')
try:
s['key1'] = { 'int': 10, 'float':9.5, 'string':'Sample data' }
8
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER
finally:
s.close()
To access the data again, open the shelf and use it like a dictionary:
import shelve
s = shelve.open('test_shelf.db')
try:
existing = s['key1']
finally:
s.close()
print existing
Shelves do not track modifications to volatile objects, by default. That means if you change the
contents of an item stored in the shelf, you must update the shelf explicitly by storing the item
again.
import shelve
s = shelve.open('test_shelf.db')
try:
9
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER
print s['key1']
s['key1']['new_value'] = 'this was not here before'
finally:
s.close()
s = shelve.open('test_shelf.db', writeback=True)
try:
print s['key1']
finally:
s.close()
6.8. Inheritance
It refers to defining a new class with little or no modification to an existing class. The new class
is called derived (or child) class and the one from which it inherits is called the base (or parent)
class.
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
Derived class inherits features from the base class, adding new features to it. This results into re-
usability of code.
class Polygon:
def __init__(self, no_of_sides):
self.n = no_of_sides
self.sides = [0 for i in range(no_of_sides)]
def inputSides(self):
self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]
10
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER
def dispSides(self):
for i in range(self.n):
print("Side",i+1,"is",self.sides[i])
class Triangle(Polygon):
def __init__(self):
Polygon.__init__(self,3)
def findArea(self):
a, b, c = self.sides
# calculate the semi-perimeter
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
class Derived1(Base):
pass
class Derived2(Derived1):
pass
6.9. Polymorphism
Sometimes an object comes in many types or forms. If we have a button, there are many
different draw outputs (round button, check button, square button, button with image) but they
11
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER
do share the same logic: onClick(). We access them using the same method . This idea is called
Polymorphism.
Polymorphism is based on the greek words Poly (many) and morphism (forms). We will create a
structure that can take or use many forms of objects.
We create two classes: Bear and Dog, both can make a distinct sound. We then make two
instances and call their action using the same method.
class Bear(object):
def sound(self):
print "Groarrr"
class Dog(object):
def sound(self):
print "Woof woof!"
def makeSound(animalType):
animalType.sound()
bearObj = Bear()
dogObj = Dog()
makeSound(bearObj)
makeSound(dogObj)
Output:
Groarrr
Woof woof!
12
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER
To overload the + sign, we will need to implement __add__() function in the class. With great
power comes great responsibility. We can do whatever we like, inside this function. But it is
sensible to return a Point object of the coordinate sum.
class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __str__(self):
return "({0},{1})".format(self.x,self.y)
def __add__(self,other):
x = self.x + other.x
y = self.y + other.y
return Point(x,y)
class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __str__(self):
return "({0},{1})".format(self.x,self.y)
13
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER
def __add__(self,other):
x = self.x + other.x
y = self.y + other.y
return Point(x,y)
Example:
class Car:
def __init__(self, name):
self.name = name
def drive(self):
raise NotImplementedError("Subclass must implement abstract method")
def stop(self):
raise NotImplementedError("Subclass must implement abstract method")
class Sportscar(Car):
def drive(self):
return 'Sportscar driving!'
def stop(self):
return 'Sportscar braking!'
class Truck(Car):
def drive(self):
return 'Truck driving slowly because heavily loaded.'
def stop(self):
return 'Truck braking!'
14
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER
cars = [Truck('Bananatruck'),
Truck('Orangetruck'),
Sportscar('Z3')]
def show(self):
raise NotImplementedError("Subclass must implement abstract method")
class Pdf(Document):
def show(self):
return 'Show pdf contents!'
class Word(Document):
def show(self):
return 'Show word contents!'
documents = [Pdf('Document1'),
Pdf('Document2'),
Word('Document3')]
15
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER
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
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
16
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER
......................
else:
If there is no exception then execute this block.
Example:
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()
6.13. Multithreading
Running several threads is similar to running several different programs concurrently, but with
the following benefits.
Multiple threads within a process share the same data space with the main thread and can
therefore share information or communicate with each other more easily than if they were
separate processes.
Threads sometimes called light-weight processes and they do not require much memory
overhead; they are cheaper than processes.
A thread has a beginning, an execution sequence, and a conclusion. It has an instruction
pointer that keeps track of where within its context it is currently running.
It can be pre-empted (interrupted)
It can temporarily be put on hold (also known as sleeping) while other threads are running -
this is called yielding.
17
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER
To spawn another thread, you need to call following method available in thread module −
thread.start_new_thread ( function, args[, kwargs] )
The threading module exposes all the methods of the thread module and provides some
additional methods −
threading.currentThread() − Returns the number of thread objects in the caller's thread control.
threading.enumerate() − Returns a list of all thread objects that are currently active.
In addition to the methods, the threading module has the Thread class that implements threading.
The methods provided by the Thread class are as follows −
run() − The run() method is the entry point for a thread.
start() − The start() method starts a thread by calling the run method.
join([time]) − The join() waits for threads to terminate.
isAlive() − The isAlive() method checks whether a thread is still executing.
getName() − The getName() method returns the name of a thread.
setName() − The setName() method sets the name of a thread.
19