Classes Objects
Classes Objects
9
https://docs.python.org/2/tutorial/datastructures.html
67
https://docs.python.org/2/library/sqlite3.html
68
Object Oriented
• A program is made up of many cooperating objects
• Instead of being the “whole program” - each object is a
little “island” within the program and cooperatively
working with other objects.
10
movies = list()
movie1 = dict()
movie1['Director'] = 'James Cameron'
movie1['Title'] = 'Avatar'
movie1['Release Date'] = '18 December
2009'
movie1['Running Time'] = '162 minutes'
movie1['Rating'] = 'PG-13'
movies.append(movie1)
movie2 = dict()
movie2['Director'] = 'David Fincher'
movie2['Title'] = 'The Social Network'
movie2['Release Date'] = '01 October 2010'
movie2['Running Time'] = '120 min'
movie2['Rating'] = 'PG-13'
movies.append(movie2)
72
keys = ['Title', 'Director', 'Rating',
'Running Time']
print '-----------'
print movies
print '-----------'
print keys
print '-----------'
73
Input
Dictionary
Object
Object
String
Objects get
created and
used Output
74
Input
Code/Data
Code/Data
Code/Data
Code/Data
Objects are
bits of code
and data Output
75
Input
Code/Data
Code/Data
Code/Data
Code/Data
Objects hide
detail - they allow
us to ignore the
detail of the “rest Output
of the program”.
76
Object
• An Object is a bit of self-contained Code and Data
• A key aspect of the Object approach is to break the
problem into smaller understandable parts (divide and
conquer)
• Objects have boundaries that allow us to ignore un-
needed detail
• We have been using objects all along: String Objects,
Integer Objects, Dictionary Objects, List Objects...
11
Definitions
12
Terminology: Class
Defines the abstract characteristics of a thing (object), including
the thing's characteristics (its attributes, fields or properties) and
the thing's behaviors (the things it can do, or methods,
operations or features). One might say that a class is a blueprint
or factory that describes the nature of something. For example,
the class Dog would consist of traits shared by all dogs, such as
breed and fur color (characteristics), and the ability to bark and
sit (behaviors).
http://en.wikipedia.org/wiki/Object-oriented_programming
78
Terminology: Class
A pattern (exemplar) of a class. The
class of Dog defines all possible dogs by
listing the characteristics and behaviors
they can have; the object Lassie is one
particular dog, with particular versions
of the characteristics. A Dog has fur;
Lassie has brown-and-white fur.
http://en.wikipedia.org/wiki/Object-oriented_programming
79
Terminology: Instance
One can have an instance of a class or a particular object. The
instance is the actual object created at runtime. In programmer
jargon, the Lassie object is an instance of the Dog class. The set
of values of the attributes of a particular object is called its state.
The object consists of state and the behavior that's defined in
the object's class.
Object and Instance are often used interchangeably.
http://en.wikipedia.org/wiki/Object-oriented_programming
13
Terminology: Method
An object's abilities. In language, methods are verbs. Lassie,
being a Dog, has the ability to bark. So bark() is one of Lassie's
methods. She may have other methods as well, for example sit()
or eat() or walk() or save_timmy(). Within the program, using a
method usually affects only one particular object; all Dogs can
bark, but you need only one particular dog to do the barking
Method and Message are often used interchangeably.
http://en.wikipedia.org/wiki/Object-oriented_programming
14
A Sample Class
15
class is a reserved This is the template
class PartyAnimal:
word. for making
x=0
PartyAnimal objects.
def party(self) : Each PartyAnimal
Each PartyAnimal self.x = self.x + 1 object has a bit of
object has a bit of print "So far",self.x data.
code.
an = PartyAnimal() Create a PartyAnimal
object.
Tell the object an.party()
to run the an.party() PartyAnimal.party(an)
party() code. an.party()
run party() *within* the object an
16
class PartyAnimal: “self” is a formal
x=0 argument that refers to
the object itself.
def party(self) :
self.x = self.x + 1 self.x is saying “x within self”
print "So far",self.x
an
self x0
an = PartyAnimal()
party()
an.party()
an.party()
an.party() self is “global within this
object”
17
Playing with dir() and type()
87
Try dir() with a String
>>> y = “Hello there”
>>> dir(y)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__',
'__le__', '__len__', '__lt__', '__repr__', '__rmod__', '__rmul__',
'__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode',
'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum',
'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind',
'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split',
'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']
88
class PartyAnimal:
x = 0 We can use dir() to find
the “capabilities” of our
def party(self) : newly created class.
self.x = self.x + 1
print "So far",self.x
an = PartyAnimal()
$ python party2.py
print "Type", type(an) Type <type 'instance'>
print "Dir ", dir(an) Dir ['__doc__',
'__module__', 'party', 'x']
89
What Are Classes Useful For?
18
Object Lifecycle
• Objects are created, used and discarded
• We have special blocks of code (methods) that get
called
• At the moment of creation (constructor)
• At the moment of destruction (destructor)
• Constructors are used a lot
• Destructors are seldom used
19
Constructor
20
class PartyAnimal:
x = 0
def __init__(self):
$ python party2.py
print "I am constructed"
I am constructed
So far 1
def party(self) : So far 2
self.x = self.x + 1 So far 3
print "So far",self.x I am destructed 3
def __del__(self):
print "I am destructed",
self.x
The constructor and
destructor are optional. The
an = PartyAnimal() constructor is typically used
an.party()
an.party() to set up variables. The
an.party() destructor is seldom used.
21
Constructor
http://en.wikipedia.org/wiki/Constructor_(computer_science)
22
Many Instances
23
class PartyAnimal:
x = 0
name = ""
def __init__(self, nam): Constructors can have
self.name = nam
print self.name,"constructed"
additional parameters.
These can be used to set
def party(self) :
self.x = self.x + 1 up instance variables for
print self.name,"party count",self.x the particular instance of
s = PartyAnimal("Sally") the class (i.e., for the
s.party()
particular object).
j = PartyAnimal("Jim")
j.party()
s.party()
25
Inheritance
• When we make a new class - we can reuse an existing
class and inherit all the capabilities of an existing class
and then add our own little bit to make our new class
• Another form of store and reuse
• Write once - reuse many times
• The new class (child) has all the capabilities of the old
class (parent) - and then some more
26
Terminology: Inheritance
http://en.wikipedia.org/wiki/Object-oriented_programming
27
class PartyAnimal: s = PartyAnimal("Sally")
x = 0 s.party()
name = ""
def __init__(self, nam):
self.name = nam
j = FootballFan("Jim")
print self.name,"constructed" j.party()
j.touchdown()
def party(self) :
self.x = self.x + 1
print self.name,"party count",self.x
28
class PartyAnimal: s = PartyAnimal("Sally")
x = 0 s.party()
name = ""
def __init__(self, nam):
self.name = nam
j = FootballFan("Jim")
print self.name,"constructed" j.party()
j.touchdown()
def party(self) :
self.x = self.x + 1
print self.name,"party count",self.x s
x
class FootballFan(PartyAnimal):
points = 0
def touchdown(self):
name: Sally
self.points = self.points + 7
self.party()
print self.name,"points",self.points
29
class PartyAnimal: s = PartyAnimal("Sally")
x = 0 s.party()
name = ""
def __init__(self, nam):
self.name = nam
j = FootballFan("Jim")
print self.name,"constructed" j.party()
j.touchdown()
def party(self) :
self.x = self.x + 1
print self.name,"party count",self.x j
x
class FootballFan(PartyAnimal):
points = 0
def touchdown(self):
name: Jim
self.points = self.points + 7
self.party() points
print self.name,"points",self.points
30
Definitions
• Class - a template - Dog
• Method or Message - A defined capability of a class - bark()
• Object or Instance - A particular instance of a class - Lassie
• Constructor - A method which is called when the instance / object
is created
• Inheritance - the ability to take a class and extend it to make a new
class.
31
Summary
32