You are on page 1of 19

Object-­‐Oriented

 
Programming  in  Python  
(Taken  and  Adapted  from  the  course  
notes  of  Dr.  Greene  of  UCD  School  of  
Computer  Science  and  InformaDcs,  
Dublin)  
Classes  and  Objects  
Object-­‐Oriented  Programming  (OOP):  A  programming  
paradigm  that  involves  designing  programs  around  
concepts  represented  as  "objects"  
•  Python  supports  OOP  through  the  provision  of  classes.  
•  Terminology  
 •  Class:  A  collecDon  of  funcDons  and  aKributes,  
 aKached  to  a  specific  name,  which  represents  an  
 abstract  concept.  
 •  AKribute:  A  named  piece  of  data  (i.e.  variable  
 associated  with  a  class.  
 •  Object:  A  single  concrete  instance  generated  from  a  
 class  
 
 
Instances  of  Classes  
Classes  can  be  viewed  as  factories  or  templates  
for  generaDng  new  object  instances.  
Each  object  instance  takes  on  the  properDes  of  
the  class  from  which  it  was  created.  
 
 
Instances  of  Classes  
CreaDng  Classes  
• Defining a class in Python is done using the class
keyword, followed
Defining   a  class  by
in  an indented
Python   block
is  done   using  with
the  cthe
lass  class
contents.
keyword,  followed  by  an  indented  block  with  the  
class  contents .  
General Format
class <Classname>:
Class data
data1 = value1
attributes
...
dataM = valueM

def <function1>(self,arg1,...,argK):
<block>
Class
...
member
functions
def <functionN>(self,arg1,...,argK):
<block>
Defining  FuncDons  in  Classes  
lass•  definition blockblock  
A  class  definiDon   can cinclude multiple
an  include   mulDple  functi
funcDons.  
ese represent the functionality or behaviors tha
•  These  
sociated represent  
with the  funcDonality  or  behaviors  
the class.
that  are  associated  with  the  class.  
>>> class Maths:
... def subtract(self,i,j):
... return i-j
...
... def add(self,x,y):
... return x+y

Argument  (self)  refers  to  the  object  itself  


ss functions differ from standard Python functions
Calling  FuncDons  in  Classes  
•  Using  Class  
ss Functions from FuncDons  
Outside from   Outside  a  Class  
a Class
FuncDons  aby
are referenced re  rusing
eferenced  
the bdoty  using  
syntax: the  dot  syntax:  
<objectName>.<methodName>()  
me>.<funcName>()

>>> m = Maths() No need to


>>> m.subtract(10,5) specify value for
5 self, Python does
>>> m.add(6,7) this automatically
13

ass Functions from Inside a Class


erring to functions
>.<funcName>()

>>> >>>
m = mMaths()
= Maths() No need
No needto to
>>> >>> Calling  FuncDons  in  Classes  
m.subtract(10,5)
m.subtract(10,5) specify value
specify valuefor for
5 5 self,self,
Python doesdoes
Python
Using  
>>>• >>>
m.add(6,7)
m.add(6,7) this this
Class  FuncDons  from  automatically
Inside   a  Class    
automatically
13 13
When  referring  to  funcDons  from  within  a  class,  we  
must  always  prefix  the  funcDon  name  with  self    
unctions
s Functions from Inside
from Inside a Class
a Class
(e.g.  self.subtract())  
to functions
ring to functions >>> >>>
class Maths:
class Maths:
class,
a class, ... ... def def
subtract(self,i,j):
subtract(self,i,j):
s prefix
ways thethe
prefix ... ... return i-j i-j
return
withwith
me selfself ... ...
ract()) )
subtract() ... ... def def
testsub(self):
testsub(self):
... ... print self.subtract(8,4)
print self.subtract(8,4)

Tell Tell
Python to use
Python function
to use function
associated withwith
associated this this
object
object
8
AKributes  
Class attribute
Class attribute
defined at top of
defined at top of >>> class Person:
>>> class Person: Instance attribute
Instance attribute
class
class ... company = "ucd"
... company = "ucd" defined
defined inside
inside a class
a class
...
... function.
function.
...
... def
def __init__(self):
__init__(self):
The
The self
self prefix
prefix is is
...
... self.age
self.age == 23
23
always
always required.
required.

>>> >>>
p1 p1 = Person()
= Person() Change
>>> p2 = Person() Changetotoinstance attribute
instance ageage
attribute
>>> p2 = Person() affects only the associated
>>> p1.age = 35 affects only the associated
>>> p1.age = 35 instance (p2)
>>> print p2.age instance (p2)
>>> 23
print p2.age
23

>>> p1 = Person()
>>> >>>
p1 p2
= Person()
= Person() Change to class attribute company
>>> >>>
p2 p1.company
= Person()= "ibm" affects
Changealltoinstances (p1 and company
class attribute p2)
>>> >>> print p2.company
p1.company = "ibm" affects all instances (p1 and p2)
'ibm'
>>> print p2.company
'ibm'
Constructor  
When an instance of a class is created, the class constructor
function is automatically called.
• •  When  
The an  instance  
constructor of  a  class  
is always named is  created,   the  class  constructor  
__init__()
funcDon  is  automaDcally  called.  
• It contains code for initializing a new instance of the class to a
•  The  cinitial
specific onstructor  
stateis  (e.g.
always  setting
named  _instance
_init__()   attribute values).
• If • noIt  constructor
contains  code  isfor   iniDalizing  
present, ana  empty
new  instance  
object of  is
the   class  to  a  
created.
specific  iniDal  state  (e.g.  seTng  instance  aKribute  values).  
>>> class Person:
Constructor function taking
... def __init__( self, s ):
... self.name = s
initial value for instance
... attribute name
... def hello( self ):
... print "Hello", self.name

>>> t = Person("John") Calls __init__()


>>> t.hello() on Person
Hello John
Inheritance  
Class  inheritance  is  designed  to  model  
relaDonships  of  the  type  "x  is  a  y"  (e.g.  "a  
triangle  is  a  shape")  
Inheritance  
The  funcDons  and  aKributes  of  a  superclass  are  
inherited  by  a  subclass.  

An  inherited  class  can  override,  modify  or  augment  the  


funcDons  and  aKributes  of  its  parent  class.  
CreaDng  Subclasses  
Simple superclass >>> class Shape:
... def __init__( self ):
... self.color = (0,0,0)

Simple subclass >>> class Rectangle(Shape): Need to call


inheriting from ... def __init__( self, w, h ): constructor
... Shape.__init__( self ) function in
Shape
... self.width = w superclass
... self.height = h
...
... def area( self ):
... return self.width*self.height

Construct
>>> r1 = Rectangle( 10, 5 )
>>> print r1.width
object instance
10
>>> print r1.height
5
>>> print r1.area()
50
>>> print r1.color Inherited
(0, 0, 0) attribute
Overriding  
 
 When  inheriDng  from  a  class,  we  can  alter  the  behavior    
 of  the  original  superclass  by  "overriding"  funcDons  (i.e.  
 declaring  funcDons  in  the  subclass  with  the  same  name).  
 
 FuncDons  in  a  subclass  take  precedence  over  funcDons    
 in  a  superclass.  
original superclass by "overriding" functions
(i.e. declaring functions in the subclass with the same name).
Overriding  
Note: Functions in a subclass take precedence over functions
in a superclass.

class CustomCounter(Counter):
class Counter: def __init__(self,size):
def __init__(self): Counter.__init__(self)
self.value = 0 self.stepsize = size

def increment(self): def increment(self):


self.value += 1 Overriding self.value += self.stepsize

>>> cc = CustomCounter(4) Calls increment()


>>> cc.increment() on CustomCounter
>>> cc.print_current() not Counter
Current value is 4
ComposiDon  
• Classes  
Classes can  
can bebe   built  
built from from  
otherother   smaller  
smaller classes,allowing  
classes, allowing us to
us  to  relationships
model model  relaDonships  
of the type of  t"x
he  has
type  a"x  
y"has  a  y”  (e.g.  a  
(e.g. a department
department   has  shas students).
tudents).  
class Department: class Student:
def __init__( self ): def __init__( self,last,first ):
self.students = [] self.lastname = last
self.firstname = first
def enroll( self, student ):
self.students.append(student)

>>> compsci = Department()


Create Student
>>> compsci.enroll( Student( "Smith", "John" ) ) instances and add
>>> compsci.enroll( Student( "Murphy", "Alice" ) ) to Department
instance
>>> for s in compsci.students:
... print "%s %s" % (s.firstname,s.lastname)
...
John Smith
Polymorphism  

Two  objects  of  different  classes  but  supporDng  


the  same  set  of  funcDons  or  aKributes  can  be  
treated  idenDcally.  
 
The  implementaDons  may  differ  internally,  but  
the  outward  "appearance"  is  the  same.  
• Two objects of different classes but supporting the same set of


Polymorphism  
functions or attributes can be treated identically.
The implementations may differ internally, but the outward
"appearance" is the same.
Two different classes that contain the function area()
class Rectangle(Shape): class Circle(Shape):
def __init__(self, w, h): def __init__(self, rad):
Shape.__init__(self) Shape.__init__(self)
self.width = w self.radius = rad
self.height = h
def area(self):
def area(self): return math.pi*(self.radius**2)
return self.width*self.height

Instances of the two classes can be >>> l = []


treated identically... >>> l.append( Rectangle(4,5) )
>>> l.append( Circle(3) )
>>> for someshape in l:
... print someshape.area()
...
Result of area() in Rectangle 20
Result of area() in Circle 28.2743338823

You might also like