Sei sulla pagina 1di 19

PRAGATI ENGINEERING COLLEGE, SURAMPALEM

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

6.3. Attributes and methods


A class by itself is of no use unless there is some functionality associated with it. Functionalities
are defined by setting attributes, which act as containers for data and functions related to those
attributes. Those functions are called methods.
Attributes:

You can define the following class with the name Snake. This class will have an attribute name.

>>> class Snake:


... name = "python" # set an attribute `name` of the class
...

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

>>> # instantiate the class Snake and assign it to variable snake


>>> snake = Snake()

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

>>> class Snake:


... name = "python"
...
... def change_name(self, new_name): # note that the first argument is self
... self.name = new_name # access the class attribute with the self keyword
...

Now, you can instantiate this class Snake with a variable snake and then change the name with
the method change_name.

>>> # instantiate the class


>>> snake = Snake()

3
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

>>> # print the current object name


>>> print(snake.name)
python

>>> # change the name using the change_name method


>>> snake.change_name("anaconda")
>>> print(snake.name)
anaconda

Instance attributes in python and the init method

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:

def __init__(self, name):


self.name = name

def change_name(self, new_name):


self.name = new_name

Now you can directly define separate attribute values for separate objects. For example,

>>> # two variables are instantiated


>>> python = Snake("python")
>>> anaconda = Snake("anaconda")

>>> # print the names of the two variables


>>> print(python.name)

4
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

python
>>> print(anaconda.name)
anaconda

6.4. Defining classes


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

An object is created with the following syntax.


emp1 = Employee("Zara", 2000)

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 −

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

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.

6.5. Design with classes


class Customer(object):
"""A customer of ABC Bank with a checking account. Customers have the
following properties:

Attributes:
name: A string representing the customer's name.
balance: A float tracking the current balance of the customer's account.
"""

def __init__(self, name):


"""Return a Customer object whose name is *name*."""

6
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

self.name = name

def set_balance(self, balance=0.0):


"""Set the customer's starting balance."""
self.balance = balance

def withdraw(self, amount):


"""Return the balance remaining after withdrawing *amount*
dollars."""
if amount > self.balance:
raise RuntimeError('Amount greater than available balance.')
self.balance -= amount
return self.balance

def deposit(self, amount):


"""Return the balance remaining after depositing *amount*
dollars."""
self.balance += amount
return self.balance

6.6. Data modelling


that represents an object. The object can be stored in a database. We can fetch it from there,
modify and push back.

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.

6.7. Persistent storage of objects


The shelve module can be used as a simple persistent storage option for Python objects
when a relational database is overkill. The shelf is accessed by keys, just as with a dictionary.
The values are pickled and written to a database created and managed by anydbm.
The simplest way to use shelve is via the DbfilenameShelf class. It uses anydbm to store the
data. You can use the class directly, or simply call shelve.open():

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

If you run both sample scripts, you should see:

>>> python shelve_create.py


>>> python shelve_existing.py

{'int': 10, 'float': 9.5, 'string': 'Sample data'}

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)

Syntax of multiple inheritance is given below.


class Base:
pass

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

6.10. Operator overloading (eq_, _str_, etc)


Python operators work for built-in classes. But same operator behaves differently with different
types. For example, the + operator will, perform arithmetic addition on two numbers, merge two
lists and concatenate two strings. This feature in Python, that allows same operator to have
different meaning according to the context is called operator overloading.

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')]

for car in cars:


print car.name + ': ' + car.drive()

6.11. Abstract classes


This class does not have any implementation but defines the structure (in form of functions) that
all forms must have. If we define the function show() then both the PdfDocument and
WordDocument must have the show() function.
class Document:
def __init__(self, name):
self.name = name

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

for document in documents:


print document.name + ': ' + document.show()

6.12. Exception handling, try block


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.
 Assertions − This would be covered in Assertions in Python.

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

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

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.activeCount() − Returns the number of thread objects that are active.

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.

6.14. Automation using Python


Various applications are listed below.
 Search for text in a file or across multiple files
 Create, update, move, and rename files and folders
 Search the Web and download online content
 Update and format data in Excel spreadsheets of any size
 Split, merge, watermark, and encrypt PDFs
 Send reminder emails and text notifications
 Fill out online forms
18
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

Getting sheets from the excel workbook is discussed below.


>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> wb.get_sheet_names()
['Sheet1', 'Sheet2', 'Sheet3']
>>> sheet = wb.get_sheet_by_name('Sheet3')
>>> sheet
<Worksheet "Sheet3">
>>> type(sheet) <class 'openpyxl.worksheet.worksheet.Worksheet'>
>>> sheet.title
'Sheet3'
>>> anotherSheet = wb.active
>>> anotherSheet
<Worksheet "Sheet1">

19

Potrebbero piacerti anche