SlideShare a Scribd company logo
Swarup Kr Ghosh
MIS Group
IIM Calcutta
swarupg1@gmail.com
 Modules and Packages
 Classes and OOPs
 Operator Overloading
 Exceptions
7/21/2017 2Swarup Kr Ghosh
 The highest-level programming structure, which packages
program code and data for reuse
 Collection of stuff defined in separate files with .py extension
◦ Functions, classes and variables
 Each file is a module, and modules import other modules to use
 Items are imported using from or import
from module import function
function()
import module
module.function()
7/21/2017 3Swarup Kr Ghosh
 Each module has its own namespace
◦ Can be used to organize variable names, i.e.
atom.position = atom.position - molecule.position
 Modules might also correspond to extensions
coded in external languages such as C, Java, or
C#
7/21/2017 4Swarup Kr Ghosh
 Code reuse
◦ Routines can be called multiple times within a program
◦ Routines can be used from multiple programs
 System Namespace partitioning
◦ Group data together with functions used for that data
 Implementing shared services or data
◦ Can provide global data structure that is accessed by
multiple subprograms
7/21/2017 5Swarup Kr Ghosh
import mymodule:
Brings all elements of mymodule
in, but must refer to as mymodule
>>> import module1
#Get module as a whole
>>> module1.printer('Hello
world!') #Qualify to get names
Hello world!
from mymodule import x:
Imports x from mymodule right
into this namespace
>>> from module1 import printer
#Copy out a variable
>>> printer('Hello world!')
#No need to qualify name
Hello world!
from mymodule import *:
Imports all elements of mymodule
into this namespace
>>> from module1 import *
#Copy out _all_ variables
>>> printer('Hello world!')
Hello world!
7/21/2017 6Swarup Kr Ghosh
 Collection of modules in directory
 Must have __init__.py file
 May contain subpackages
 Import syntax:
◦ import dir1.dir2.mod
◦ from dir1.dir2.mod import x
◦ from dir1.dir2.mod import foo: print foo()
◦ from dir1.dir2 import mod: print mod.foo()
◦ import dir1.dir2.mod: print dir1.dir2.mod.foo()
◦ import dir1.dir2.mod as mod: print mod.foo()
7/21/2017 7Swarup Kr Ghosh
7/21/2017 8Swarup Kr Ghosh
 ‘import’ refer to load a file on request
 The files ‘a.py, b.py, c.py’ are chosen to be simple
text
def spam(text): # File b.py
print(text, 'spam')
import b # File a.py
b.spam('gumby') # Prints "gumby spam"
7/21/2017 9Swarup Kr Ghosh
class name:
"documentation"
statements
-or-
class name(base1, base2, ...):
...
Most, statements are method definitions:
def name(self, arg1, arg2, ...):
...
May also be class variable assignments
7/21/2017 10Swarup Kr Ghosh
 Instances of class
 A software item that contains variables and methods
x = Stack()
 To use methods of the instance, call using dot notation:
x.empty()
x.push(1)
x.empty()
x.push("hello")
x.pop()
 To inspect instance variables, use dot notation:
x.items
7/21/2017 11Swarup Kr Ghosh
class Stack:
"A well-known data structure…"
def __init__(self): #constructor
self.items = []
def push(self, x):
self.items.append(x) #the sky is the limit
def pop(self):
x = self.items[-1] #what happens if it’s empty?
del self.items[-1]
return x
def empty(self):
return len(self.items) == 0 #Boolean result
7/21/2017 12Swarup Kr Ghosh
 Object Oriented Design focuses on:
 Encapsulation:
◦ binding (or wrapping) code and data together into a single unit
is known as encapsulation
◦ dividing the code into a public interface, and a private
implementation of that interface
 Abstraction:
◦ hiding internal details and showing functionality, e.g.: phone
call, we don't know the internal processing
 Polymorphism:
◦ the ability to overload standard operators so that they have
appropriate behavior based on their context
◦ one task is performed by different ways
 Inheritance:
◦ the ability to create subclasses that contain specializations of
their parents
7/21/2017 13Swarup Kr Ghosh
>>> class FirstClass: #Define a class object
def setdata(self, value): #Define class's methods
self.data = value #self is the instance
def display(self):
print(self.data) #self.data: per instance
>>> x = FirstClass() #Make two instances
>>> y = FirstClass() #Each is a new namespace
>>> x.setdata("King Arthur") #Call methods: self is x
>>> y.setdata(3.14159) #Runs: FirstClass.setdata()
>>> x.display() #self.data differs in each instance
King Arthur
>>> y.display() #Runs: FirstClass.display(y)
3.14159
7/21/2017Swarup Kr Ghosh 14
7/21/2017Swarup Kr Ghosh 15
class atom(object):
def __init__(self,atno,x,y,z):
self.atno = atno
self.position = (x,y,z)
def symbol(self): #a class method
return Atno_to_Symbol[atno]
def __repr__(self): #overloads printing
return '%d %10.4f %10.4f %10.4f' %
(self.atno, self.position[0],
self.position[1],self.position[2])
>>> at = atom(6,0.0,1.0,2.0)
>>> print at
6 0.0000 1.0000 2.0000
>>> at.symbol()
'C'
7/21/2017 16Swarup Kr Ghosh
 Overloaded the default constructor
 Defined class variables (atno, position) that are
persistent and local to the atom object
 Good way to manage shared memory:
◦ instead of passing long lists of arguments, encapsulate
some of this data into an object, and pass the object.
◦ much cleaner programs result
 Overloaded the print operator
 We now want to use the atom class to build
molecules........
7/21/2017 17Swarup Kr Ghosh
class molecule:
def __init__(self,name='Generic'):
self.name = name
self.atomlist = []
def addatom(self,atom):
self.atomlist.append(atom)
def __repr__(self):
str = 'This is a molecule named %sn' % self.name
str = str+'It has %d atomsn' % len(self.atomlist)
for atom in self.atomlist:
str = str + `atom` + 'n'
return str
7/21/2017 18Swarup Kr Ghosh
>>> mol = molecule('Water')
>>> at = atom(8,0.,0.,0.)
>>> mol.addatom(at)
>>> mol.addatom(atom(1,0.,0.,1.))
>>> mol.addatom(atom(1,0.,1.,0.))
>>> print mol
This is a molecule named Water
It has 3 atoms
8 0.000 0.000 0.000
1 0.000 0.000 1.000
1 0.000 1.000 0.000
 Note that the print function calls the atoms print function
◦ Code reuse: only have to type the code that prints an atom once;
this means that if you change the atom specification, you only
have one place to update.
7/21/2017 19Swarup Kr Ghosh
class LimitedStack(FancyStack):
"fancy stack with limit on stack size"
def __init__(self, limit):
self.limit = limit
FancyStack.__init__(self) #base class constructor
def push(self, x):
assert len(self.items) < self.limit
FancyStack.push(self, x) #"super" method call
7/21/2017 20Swarup Kr Ghosh
 Process by which one object acquires the properties of
another object
 E.g. First define Class FirstClass (previous e.g.)
>>> class SecondClass(FirstClass): #Inherits setdata
def display(self): #changes display
print('Current value = "%s"' % self.data)
>>> z = SecondClass()
>>> z.setdata(42) #Finds setdata in FirstClass
>>> z.display() #Finds overridden method in SecondClass
Current value = "42“
>>> x.display() #x is still a FirstClass instance (old message)
King Arthur
7/21/2017Swarup Kr Ghosh 21
7/21/2017Swarup Kr Ghosh 22
class ThirdClass(SecondClass): #Inherit from SecondClass
def __init__(self, value): #On "ThirdClass(value)"
self.data = value
def __add__(self, other): #On "self + other"
return ThirdClass(self.data + other)
def __str__(self): #On "print(self)", "str()"
return '[ThirdClass: %s]' % self.data
def mul(self, other): #In-place change: named
self.data *= other
>>> a = ThirdClass('abc') # __init__ called
>>> a.display() #Inherited method called
Current value = "abc"
>>> print(a) #__str__:returns display string
[ThirdClass: abc]
>>> b = a + 'xyz' #__add__:makes a new instance
>>> b.display() #b has all ThirdClass methods
Current value = "abcxyz"
>>> print(b) #__str__: returns display string
[ThirdClass: abcxyz]
>>> a.mul(3) #mul: changes instance in place
>>> print(a)
[ThirdClass: abcabcabc]
7/21/2017Swarup Kr Ghosh 23
 Three attributes in Python:
 __init__: to create new instance of object
 __add__: to make a new instance when ‘+’ appear
in class
 __str__: to print the object (print string)
7/21/2017Swarup Kr Ghosh 24
class Connection:
verbose = 0 #class variable
def __init__(self, host):
self.host = host #instance variable
def debug(self, v):
self.verbose = v #make instance
variable!
def connect(self):
if self.verbose: #class or instance
variable?
print ("connecting to", self.host)
7/21/2017 25Swarup Kr Ghosh
 On use via instance (self.x), search order:
◦ (1) instance, (2) class, (3) base classes
◦ this also works for method lookup
 On assignment via instance (self.x = ...):
◦ always makes an instance variable
 Class variables "default" for instance variables
 But...!
◦ mutable class variable: one copy shared by all
◦ mutable instance variable: each instance its own
7/21/2017 26Swarup Kr Ghosh
 Special kind of method that determines how an object
is initialized when created
class Person:
def __init__(self, name, job=None, pay=0):
#Const takes 3 arguments
self.name = name #Fill out fields when created
self.job = job #self is the new instance object
self.pay = pay
bob = Person('Bob Smith') #Test the class
sue = Person('Sue Jones', job='dev', pay=100000)
#Runs __init__ automatically
print(bob.name, bob.pay) #Fetch attached attributes
print(sue.name, sue.pay) #sue's and bob's attrs differ
7/21/2017Swarup Kr Ghosh 27
 “Operator overloading” simply means intercepting
built-in operations in a class’s methods
 Classes can overload all Python expression operators
 Classes can also overload built-in operations such as
printing, function calls, attribute access, etc
 Overloading makes class instances act more like built-
in types
 Overloading is implemented by providing specially
named methods in a class
7/21/2017Swarup Kr Ghosh 28
# File number.py
class Number:
def __init__(self, start): #On Number(start)
self.data = start
def __sub__(self, other): #On instance - other
return Number(self.data - other) #Result is a new instance
>>> from number import Number #Fetch class from module
>>> X = Number(5) #Number.__init__(X, 5)
>>> Y = X - 2 #Number.__sub__(X, 2)
>>> Y.data #Y is new Number instance
3
7/21/2017Swarup Kr Ghosh 29
7/21/2017Swarup Kr Ghosh 30
 An event occurs during the execution of program
 Disrupts normal flow of program’s instruction
 It must be handled
try:
statement1
statement2
…………
Except IOError:
statement
7/21/2017Swarup Kr Ghosh 31
 Error handling
 Event notification
 Special-case handling
 Termination actions
 Unusual control flows
7/21/2017Swarup Kr Ghosh 32
 try/except:
◦ Catch and recover from exceptions raised by Python, or
by programmer
 try/finally:
◦ Perform cleanup actions, whether exceptions occur or
not
 raise:
◦ Trigger an exception manually in your code
 assert:
◦ Conditionally trigger an exception in code
7/21/2017Swarup Kr Ghosh 33
7/21/2017Swarup Kr Ghosh 34
def kelTocel(t):
assert(t>=0), “so cool”
x=((t-273)*1.8)+32
print(“Result=“,x)
return
o/p: kelTocel(100)  -279.4000
kelTocel(-20)  assertionError
def kelTocel(t):
try:
assert(t>=0), “so cool”
x=((t-273)*1.8)+32
print(“Result=“,x)
except AssertionError:
print(“Give positive value")
return
7/21/2017Swarup Kr Ghosh 35
def tem_convert(var):
try:
x=1/var
return(x)
except ZeroDivisionError:
print("argument dont match")
return
7/21/2017Swarup Kr Ghosh 36
try:
f=open("kmean3.txt","w")
f.write("this is my test file")
finally:
print("Cant find file")
f.close()
7/21/2017Swarup Kr Ghosh 37
7/21/2017Swarup Kr Ghosh 38

More Related Content

PPTX
Python lec5
PPTX
Making Java Groovy (JavaOne 2013)
KEY
Clojure Intro
PDF
Spock: A Highly Logical Way To Test
PDF
Grails/Groovyによる開発事例紹介
ODP
Turtle Graphics in Groovy
PDF
Pune Clojure Course Outline
PDF
Backbone.js: Run your Application Inside The Browser
Python lec5
Making Java Groovy (JavaOne 2013)
Clojure Intro
Spock: A Highly Logical Way To Test
Grails/Groovyによる開発事例紹介
Turtle Graphics in Groovy
Pune Clojure Course Outline
Backbone.js: Run your Application Inside The Browser

What's hot (20)

PPTX
Python GC
PDF
360|iDev
PDF
Functional Programming with Groovy
PDF
Fun Teaching MongoDB New Tricks
PPTX
Groovy!
KEY
(map Clojure everyday-tasks)
PPTX
Config BuildConfig
PDF
Dynamic C++ ACCU 2013
PDF
Dynamic C++ Silicon Valley Code Camp 2012
PDF
Python in 90 minutes
PDF
Fun never stops. introduction to haskell programming language
PDF
groovy databases
PDF
Application-Specific Models and Pointcuts using a Logic Meta Language
PDF
Clojure for Java developers - Stockholm
PDF
Look Ma, “update DB to HTML5 using C++”, no hands! 
PDF
What can be done with Java, but should better be done with Erlang (@pavlobaron)
PDF
JRuby hacking guide
PPTX
Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant)
ZIP
Pig Introduction to Pig
PDF
Python and sysadmin I
Python GC
360|iDev
Functional Programming with Groovy
Fun Teaching MongoDB New Tricks
Groovy!
(map Clojure everyday-tasks)
Config BuildConfig
Dynamic C++ ACCU 2013
Dynamic C++ Silicon Valley Code Camp 2012
Python in 90 minutes
Fun never stops. introduction to haskell programming language
groovy databases
Application-Specific Models and Pointcuts using a Logic Meta Language
Clojure for Java developers - Stockholm
Look Ma, “update DB to HTML5 using C++”, no hands! 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
JRuby hacking guide
Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant)
Pig Introduction to Pig
Python and sysadmin I
Ad

Similar to Python lec4 (20)

PPTX
Python OOPs
PDF
Lecture 01 - Basic Concept About OOP With Python
PPT
Introduction to Python - Part Three
PPTX
Python advance
PPTX
OOP Concepts Python with code refrences.pptx
PDF
Python unit 3 m.sc cs
PPT
Chap 3 Python Object Oriented Programming - Copy.ppt
PPTX
classes and objects of python object oriented
PPTX
مقدمة بايثون .pptx
PPTX
object oriented porgramming using Java programming
PPTX
software construction and development week 3 Python lists, tuples, dictionari...
PPTX
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
PPTX
Regex,functions, inheritance,class, attribute,overloding
PPTX
Object Oriented Programming.pptx
PPT
Python3
PDF
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
PPTX
Python 2. classes- cruciql for students objects1.pptx
PPT
07slide.ppt
Python OOPs
Lecture 01 - Basic Concept About OOP With Python
Introduction to Python - Part Three
Python advance
OOP Concepts Python with code refrences.pptx
Python unit 3 m.sc cs
Chap 3 Python Object Oriented Programming - Copy.ppt
classes and objects of python object oriented
مقدمة بايثون .pptx
object oriented porgramming using Java programming
software construction and development week 3 Python lists, tuples, dictionari...
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
Regex,functions, inheritance,class, attribute,overloding
Object Oriented Programming.pptx
Python3
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python 2. classes- cruciql for students objects1.pptx
07slide.ppt
Ad

Recently uploaded (20)

PDF
Pre independence Education in Inndia.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Institutional Correction lecture only . . .
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Insiders guide to clinical Medicine.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Pharma ospi slides which help in ospi learning
PPTX
master seminar digital applications in india
Pre independence Education in Inndia.pdf
O7-L3 Supply Chain Operations - ICLT Program
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Microbial disease of the cardiovascular and lymphatic systems
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Institutional Correction lecture only . . .
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Renaissance Architecture: A Journey from Faith to Humanism
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Microbial diseases, their pathogenesis and prophylaxis
Insiders guide to clinical Medicine.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Supply Chain Operations Speaking Notes -ICLT Program
2.FourierTransform-ShortQuestionswithAnswers.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
01-Introduction-to-Information-Management.pdf
Pharma ospi slides which help in ospi learning
master seminar digital applications in india

Python lec4

  • 1. Swarup Kr Ghosh MIS Group IIM Calcutta swarupg1@gmail.com
  • 2.  Modules and Packages  Classes and OOPs  Operator Overloading  Exceptions 7/21/2017 2Swarup Kr Ghosh
  • 3.  The highest-level programming structure, which packages program code and data for reuse  Collection of stuff defined in separate files with .py extension ◦ Functions, classes and variables  Each file is a module, and modules import other modules to use  Items are imported using from or import from module import function function() import module module.function() 7/21/2017 3Swarup Kr Ghosh
  • 4.  Each module has its own namespace ◦ Can be used to organize variable names, i.e. atom.position = atom.position - molecule.position  Modules might also correspond to extensions coded in external languages such as C, Java, or C# 7/21/2017 4Swarup Kr Ghosh
  • 5.  Code reuse ◦ Routines can be called multiple times within a program ◦ Routines can be used from multiple programs  System Namespace partitioning ◦ Group data together with functions used for that data  Implementing shared services or data ◦ Can provide global data structure that is accessed by multiple subprograms 7/21/2017 5Swarup Kr Ghosh
  • 6. import mymodule: Brings all elements of mymodule in, but must refer to as mymodule >>> import module1 #Get module as a whole >>> module1.printer('Hello world!') #Qualify to get names Hello world! from mymodule import x: Imports x from mymodule right into this namespace >>> from module1 import printer #Copy out a variable >>> printer('Hello world!') #No need to qualify name Hello world! from mymodule import *: Imports all elements of mymodule into this namespace >>> from module1 import * #Copy out _all_ variables >>> printer('Hello world!') Hello world! 7/21/2017 6Swarup Kr Ghosh
  • 7.  Collection of modules in directory  Must have __init__.py file  May contain subpackages  Import syntax: ◦ import dir1.dir2.mod ◦ from dir1.dir2.mod import x ◦ from dir1.dir2.mod import foo: print foo() ◦ from dir1.dir2 import mod: print mod.foo() ◦ import dir1.dir2.mod: print dir1.dir2.mod.foo() ◦ import dir1.dir2.mod as mod: print mod.foo() 7/21/2017 7Swarup Kr Ghosh
  • 9.  ‘import’ refer to load a file on request  The files ‘a.py, b.py, c.py’ are chosen to be simple text def spam(text): # File b.py print(text, 'spam') import b # File a.py b.spam('gumby') # Prints "gumby spam" 7/21/2017 9Swarup Kr Ghosh
  • 10. class name: "documentation" statements -or- class name(base1, base2, ...): ... Most, statements are method definitions: def name(self, arg1, arg2, ...): ... May also be class variable assignments 7/21/2017 10Swarup Kr Ghosh
  • 11.  Instances of class  A software item that contains variables and methods x = Stack()  To use methods of the instance, call using dot notation: x.empty() x.push(1) x.empty() x.push("hello") x.pop()  To inspect instance variables, use dot notation: x.items 7/21/2017 11Swarup Kr Ghosh
  • 12. class Stack: "A well-known data structure…" def __init__(self): #constructor self.items = [] def push(self, x): self.items.append(x) #the sky is the limit def pop(self): x = self.items[-1] #what happens if it’s empty? del self.items[-1] return x def empty(self): return len(self.items) == 0 #Boolean result 7/21/2017 12Swarup Kr Ghosh
  • 13.  Object Oriented Design focuses on:  Encapsulation: ◦ binding (or wrapping) code and data together into a single unit is known as encapsulation ◦ dividing the code into a public interface, and a private implementation of that interface  Abstraction: ◦ hiding internal details and showing functionality, e.g.: phone call, we don't know the internal processing  Polymorphism: ◦ the ability to overload standard operators so that they have appropriate behavior based on their context ◦ one task is performed by different ways  Inheritance: ◦ the ability to create subclasses that contain specializations of their parents 7/21/2017 13Swarup Kr Ghosh
  • 14. >>> class FirstClass: #Define a class object def setdata(self, value): #Define class's methods self.data = value #self is the instance def display(self): print(self.data) #self.data: per instance >>> x = FirstClass() #Make two instances >>> y = FirstClass() #Each is a new namespace >>> x.setdata("King Arthur") #Call methods: self is x >>> y.setdata(3.14159) #Runs: FirstClass.setdata() >>> x.display() #self.data differs in each instance King Arthur >>> y.display() #Runs: FirstClass.display(y) 3.14159 7/21/2017Swarup Kr Ghosh 14
  • 16. class atom(object): def __init__(self,atno,x,y,z): self.atno = atno self.position = (x,y,z) def symbol(self): #a class method return Atno_to_Symbol[atno] def __repr__(self): #overloads printing return '%d %10.4f %10.4f %10.4f' % (self.atno, self.position[0], self.position[1],self.position[2]) >>> at = atom(6,0.0,1.0,2.0) >>> print at 6 0.0000 1.0000 2.0000 >>> at.symbol() 'C' 7/21/2017 16Swarup Kr Ghosh
  • 17.  Overloaded the default constructor  Defined class variables (atno, position) that are persistent and local to the atom object  Good way to manage shared memory: ◦ instead of passing long lists of arguments, encapsulate some of this data into an object, and pass the object. ◦ much cleaner programs result  Overloaded the print operator  We now want to use the atom class to build molecules........ 7/21/2017 17Swarup Kr Ghosh
  • 18. class molecule: def __init__(self,name='Generic'): self.name = name self.atomlist = [] def addatom(self,atom): self.atomlist.append(atom) def __repr__(self): str = 'This is a molecule named %sn' % self.name str = str+'It has %d atomsn' % len(self.atomlist) for atom in self.atomlist: str = str + `atom` + 'n' return str 7/21/2017 18Swarup Kr Ghosh
  • 19. >>> mol = molecule('Water') >>> at = atom(8,0.,0.,0.) >>> mol.addatom(at) >>> mol.addatom(atom(1,0.,0.,1.)) >>> mol.addatom(atom(1,0.,1.,0.)) >>> print mol This is a molecule named Water It has 3 atoms 8 0.000 0.000 0.000 1 0.000 0.000 1.000 1 0.000 1.000 0.000  Note that the print function calls the atoms print function ◦ Code reuse: only have to type the code that prints an atom once; this means that if you change the atom specification, you only have one place to update. 7/21/2017 19Swarup Kr Ghosh
  • 20. class LimitedStack(FancyStack): "fancy stack with limit on stack size" def __init__(self, limit): self.limit = limit FancyStack.__init__(self) #base class constructor def push(self, x): assert len(self.items) < self.limit FancyStack.push(self, x) #"super" method call 7/21/2017 20Swarup Kr Ghosh
  • 21.  Process by which one object acquires the properties of another object  E.g. First define Class FirstClass (previous e.g.) >>> class SecondClass(FirstClass): #Inherits setdata def display(self): #changes display print('Current value = "%s"' % self.data) >>> z = SecondClass() >>> z.setdata(42) #Finds setdata in FirstClass >>> z.display() #Finds overridden method in SecondClass Current value = "42“ >>> x.display() #x is still a FirstClass instance (old message) King Arthur 7/21/2017Swarup Kr Ghosh 21
  • 23. class ThirdClass(SecondClass): #Inherit from SecondClass def __init__(self, value): #On "ThirdClass(value)" self.data = value def __add__(self, other): #On "self + other" return ThirdClass(self.data + other) def __str__(self): #On "print(self)", "str()" return '[ThirdClass: %s]' % self.data def mul(self, other): #In-place change: named self.data *= other >>> a = ThirdClass('abc') # __init__ called >>> a.display() #Inherited method called Current value = "abc" >>> print(a) #__str__:returns display string [ThirdClass: abc] >>> b = a + 'xyz' #__add__:makes a new instance >>> b.display() #b has all ThirdClass methods Current value = "abcxyz" >>> print(b) #__str__: returns display string [ThirdClass: abcxyz] >>> a.mul(3) #mul: changes instance in place >>> print(a) [ThirdClass: abcabcabc] 7/21/2017Swarup Kr Ghosh 23
  • 24.  Three attributes in Python:  __init__: to create new instance of object  __add__: to make a new instance when ‘+’ appear in class  __str__: to print the object (print string) 7/21/2017Swarup Kr Ghosh 24
  • 25. class Connection: verbose = 0 #class variable def __init__(self, host): self.host = host #instance variable def debug(self, v): self.verbose = v #make instance variable! def connect(self): if self.verbose: #class or instance variable? print ("connecting to", self.host) 7/21/2017 25Swarup Kr Ghosh
  • 26.  On use via instance (self.x), search order: ◦ (1) instance, (2) class, (3) base classes ◦ this also works for method lookup  On assignment via instance (self.x = ...): ◦ always makes an instance variable  Class variables "default" for instance variables  But...! ◦ mutable class variable: one copy shared by all ◦ mutable instance variable: each instance its own 7/21/2017 26Swarup Kr Ghosh
  • 27.  Special kind of method that determines how an object is initialized when created class Person: def __init__(self, name, job=None, pay=0): #Const takes 3 arguments self.name = name #Fill out fields when created self.job = job #self is the new instance object self.pay = pay bob = Person('Bob Smith') #Test the class sue = Person('Sue Jones', job='dev', pay=100000) #Runs __init__ automatically print(bob.name, bob.pay) #Fetch attached attributes print(sue.name, sue.pay) #sue's and bob's attrs differ 7/21/2017Swarup Kr Ghosh 27
  • 28.  “Operator overloading” simply means intercepting built-in operations in a class’s methods  Classes can overload all Python expression operators  Classes can also overload built-in operations such as printing, function calls, attribute access, etc  Overloading makes class instances act more like built- in types  Overloading is implemented by providing specially named methods in a class 7/21/2017Swarup Kr Ghosh 28
  • 29. # File number.py class Number: def __init__(self, start): #On Number(start) self.data = start def __sub__(self, other): #On instance - other return Number(self.data - other) #Result is a new instance >>> from number import Number #Fetch class from module >>> X = Number(5) #Number.__init__(X, 5) >>> Y = X - 2 #Number.__sub__(X, 2) >>> Y.data #Y is new Number instance 3 7/21/2017Swarup Kr Ghosh 29
  • 31.  An event occurs during the execution of program  Disrupts normal flow of program’s instruction  It must be handled try: statement1 statement2 ………… Except IOError: statement 7/21/2017Swarup Kr Ghosh 31
  • 32.  Error handling  Event notification  Special-case handling  Termination actions  Unusual control flows 7/21/2017Swarup Kr Ghosh 32
  • 33.  try/except: ◦ Catch and recover from exceptions raised by Python, or by programmer  try/finally: ◦ Perform cleanup actions, whether exceptions occur or not  raise: ◦ Trigger an exception manually in your code  assert: ◦ Conditionally trigger an exception in code 7/21/2017Swarup Kr Ghosh 33
  • 35. def kelTocel(t): assert(t>=0), “so cool” x=((t-273)*1.8)+32 print(“Result=“,x) return o/p: kelTocel(100)  -279.4000 kelTocel(-20)  assertionError def kelTocel(t): try: assert(t>=0), “so cool” x=((t-273)*1.8)+32 print(“Result=“,x) except AssertionError: print(“Give positive value") return 7/21/2017Swarup Kr Ghosh 35
  • 37. try: f=open("kmean3.txt","w") f.write("this is my test file") finally: print("Cant find file") f.close() 7/21/2017Swarup Kr Ghosh 37