14 Objects
14 Objects
Charles Severance
Object
String
Objects get
created and
used Output
Input
Code/Data
Code/Data
Code/Data
Code/Data
Objects are
bits of code
and data Output
Input
Code/Data
Code/Data
Code/Data
Code/Data
Objects hide detail -
they allow the “rest
of the program” to
ignore the detail Output
about “us”.
Definitions
• Class - a template
• Method or Message - A defined capability of a class
• Field or attribute- A bit of data in a class
• Constructor – Code that runs when an object is created
• Object or Instance - A particular instance of a class
• Inheritance - The ability to extend a class to make a new
class.
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).
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
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
http://en.wikipedia.org/wiki/Object-oriented_programming
Some Python Objects
>>> dir(x)
>>> x = 'abc' [ … 'capitalize', 'casefold', 'center', 'count',
>>> type(x) 'encode', 'endswith', 'expandtabs', 'find',
<class 'str'> 'format', … 'lower', 'lstrip', 'maketrans',
>>> type(2.5) 'partition', 'replace', 'rfind', 'rindex', 'rjust',
<class 'float'> 'rpartition', 'rsplit', 'rstrip', 'split',
>>> type(2) 'splitlines', 'startswith', 'strip', 'swapcase',
<class 'int'> 'title', 'translate', 'upper', 'zfill']
>>> y = list() >>> dir(y)
>>> type(y) [… 'append', 'clear', 'copy', 'count', 'extend',
<class 'list'> 'index', 'insert', 'pop', 'remove', 'reverse',
>>> z = dict() 'sort']
>>> type(z) >>> dir(z)
<class 'dict'> […, 'clear', 'copy', 'fromkeys', 'get', 'items',
'keys', 'pop', 'popitem', 'setdefault', 'update',
'values']
A Sample Class
This is the template
class is a reserved class PartyAnimal: for making
word x=0 PartyAnimal objects
an = PartyAnimal()
$ python party3.py
print("Type", type(an)) Type <class '__main__.PartyAnimal'>
print("Dir ", dir(an)) Dir ['__class__', ... 'party', 'x']
Try dir() with a String
>>> x = 'Hello there'
>>> dir(x)
['__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']
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
Constructor
The primary purpose of the constructor is to set up some
instance variables to have the proper initial values when
the object is created
def __del__(self):
print('I am destructed', self.x)
an = PartyAnimal()
The constructor and destructor are
an.party() optional. The constructor is
an.party() typically used to set up variables.
an = 42 The destructor is seldom used.
print('an contains',an)
Many Instances
• We can create lots of objects - the class is the template
for the object
• We can store each distinct object in its own variable
• We call this having multiple instances of the same class
• Each instance has its own copy of the instance variables
Constructors can have
class PartyAnimal:
x = 0 additional parameters.
name = "" These can be used to set up
def __init__(self, z): instance variables for the
self.name = z
particular instance of the
print(self.name,"constructed")
class (i.e., for the particular
def party(self) : object).
self.x = self.x + 1
print(self.name,"party count",self.x)
s = PartyAnimal("Sally")
j = PartyAnimal("Jim")
s.party()
j.party()
s.party() party5.py
class PartyAnimal:
x = 0 We have two
name = ""
def __init__(self, z):
independent s x: 0
self.name = z instances
print(self.name,"constructed") name: Sally
def party(self) :
self.x = self.x + 1
print(self.name,"party count",self.x) j
x: 0
s = PartyAnimal("Sally")
j = PartyAnimal("Jim")
name: Jim
s.party() Sally constructed
j.party() Jim constructed
s.party() Sally party count 1
Jim party count 1
Sally party count 2
Demo 02
Demo 03
Demo 03
Inheritance
‘Subclasses’ are more specialized versions of a class, which
inherit attributes and behaviors from their parent classes, and
can introduce their own.
• 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
class PartyAnimal: s = PartyAnimal("Sally")
x = 0 s.party()
name = ""
def __init__(self, nam): j = FootballFan("Jim")
self.name = nam j.party()
print(self.name,"constructed") j.touchdown()
def party(self) :
self.x = self.x + 1
print(self.name,"party count",self.x)
class FootballFan(PartyAnimal):
points = 0
def touchdown(self):
self.points = self.points + 7
self.party()
print(self.name,"points",self.points)
Demo 04
Demo 04
Demo 05
Summary
• Object Oriented programming is a very structured
approach to code reuse