Python Objects
Charles Severance
Python for Eve body
[Link]
Warning
• is lecture is ve much about de nitions and mechanics
for objects
• is lecture is a lot more about “how it works” and less
about “how you use it”
• You won’t get the entire picture until this is all looked at
in the context of a real problem
• So please suspend disbelief and learn technique for the
next 40 or so slides…
[Link]
[Link] /[Link]
Lets Sta with Programs
Europe oor? 0
inp = input('Europe oor?')
usf = int(inp) + 1
US oor 1
print('US oor', usf)
Input Process Output
Object Oriented
•A program is made up of many cooperating objects
•isInstead “
of being the whole program - each object
”
“ ”
a little island within the program and
cooperatively working with other objects
•working
A program is made up of one or more objects
together - objects make use of each other s
’
capabilities
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 pa s (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, Dictiona Objects, List Objects...
Input Dictiona
Object
Object
String
Objects get
created and
used Output
Input Code/Data
Code/Dat
a
Code/Data
Code/Dat
a
Objects are
bits of code
and data Output
Input Code/Data
Code/Dat
a
Code/Data
Code/Dat
Objects hide detail a
- they allow us to
ignore the detail of
the “rest of the Output
program”.
Input Code/Data
Code/Dat
a
Code/Data
Code/Dat
Objects hide detail a
- they allow the
rest of the program”
Output
“
to ignore the detail
about “us”.
De nitions
• Class - a template
• Method or Message - A de ned capability of a class
• Field or attribute- A bit of data in a class
• Object or Instance - A pa icular instance of a class
Terminology: Class
De nes the abstract characteristics of a thing (object), including the
thing's characteristics (its attributes, elds or prope ies) 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 facto 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).
[Link]
Terminology: Instance
One can have an instance of a class or a pa icular object.
e instance is the actual object created at runtime. In
programmer jargon, the Lassie object is an instance of the
Dog class. e set of values of the attributes of a pa icular
object is called its state. e object consists of state and
the behavior that's de ned in the object's class.
Object and Instance are often used interchangeably.
[Link]
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
a ects only one pa icular object; all Dogs can bark, but you need
only one pa icular dog to do the barking
Method and Message are often used interchangeably.
[Link]
>>> x = 'abc'
Some Python Objects
>>> dir(x)
[ … 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith',
>>> type(x) 'expandtabs', ' nd', 'format', … 'lower', 'lstrip', 'maketrans', 'pa ition',
<class 'str'> 'replace', ' ind', 'rindex', 'rjust', 'rpa ition', 'rsplit', 'rstrip', 'split', 'splitlines',
>>> type(2.5) 'sta swith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'z ll']
<class ' oat'> >>> dir(y)
>>> type(2) [… 'append', 'clear', 'copy', 'count', 'extend', 'index', 'inse ', 'pop', 'remove',
<class 'int'> 'reverse', 'so ']
>>> y = list() >>> dir(z)
>>> type(y) […, 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault',
<class 'list'> 'update', 'values']
>>> z = dict()
>>> type(z)
<class 'dict'>
A Sample Class
class is a rese ed class Pa yAnimal: When the object is
word that de nes a constructed, a
template for making def __init(self)__: specially named
objects self.x = 0 method is called to
Each Pa yAnimal def pa y(self) : allocate and
object has a bit of self.x = self.x + 1 initialize attributes.
code print("So far",self.x) Construct a
an = Pa yAnimal() Pa yAnimal object
and store in an
[Link] y()
Tell the an [Link] y() Pa [Link] y(an)
object to run [Link] y()
the pa y() code
within it
class Pa yAnimal: $ python pa [Link]
def __init(self)__:
self.x = 0
def pa y(self) :
self.x = self.x + 1
print("So far",self.x)
an = Pa yAnimal()
[Link] y()
[Link] y()
[Link] y()
class Pa yAnimal: $ python pa [Link]
def __init(self)__:
self.x = 0
def pa y(self) :
self.x = self.x + 1
print("So far",self.x) an
an = Pa yAnimal() x 0
[Link] y()
[Link] y()
pa y()
[Link] y()
class Pa yAnimal: $ python pa [Link]
def __init(self)__: So far 1
self.x = 0 So far 2
def pa y(self) :
So far 3
self.x = self.x + 1
print("So far",self.x) an
an = Pa yAnimal() self x
[Link] y()
[Link] y()
pa y()
[Link] y()
Pa [Link] y(an)
Playing with dir() and type()
A Nerdy Way to Find Capabilities
• e dir() command lists
capabilities >>> y = list()
>>> type(y)
• Ignore the ones with underscores <class 'list'>
- these are used by Python itself >>> dir(y)
['__add__', '__class__', '__class_getitem__',
• e rest are real operations that '__contains__', '__delattr__', '__delitem__',
'__dir__', '__doc__', '__eq__', ... 'append',
the object can pe orm 'clear', 'copy', 'count', 'extend', 'index',
'inse ', 'pop', 'remove', 'reverse', 'so ']
• It is like type() - it tells us >>>
something *about* a variable
class Pa yAnimal: We can use dir() to
def __init__(self): nd the “capabilities”
self.x = 0 of our newly created
def pa y(self) : class.
self.x = self.x + 1
print("So far",self.x)
an = Pa yAnimal() $ python pa [Link]
print("Type", type(an)) Type <class '__main__.Pa yAnimal'>
print("Dir ", dir(an)) Dir ['__class__', ... 'pa y', 'x']
print ("Type", type(an.x)) Type <class 'int'>
print ("Type", type([Link] y)) Type <class 'method'>
pa [Link]
T dir() with a String
>>> x = 'Hello there'
>>> dir(x)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__',
'__hash__', '__init__', '__init_subclass__', ...'capitalize', 'casefold', 'center', 'count', 'encode',
'endswith', 'expandtabs', ' nd', 'format', 'format_map', 'index', 'isalnum', 'isalpha',
'isascii', 'isdecimal', 'isdigit', 'isidenti er', 'islower', 'isnumeric', 'isprintable', 'isspace',
'istitle', 'isupper', 'removesu x', 'replace', ' ind', 'rindex', 'rjust', 'rpa ition', 'rsplit',
'rstrip', 'split', 'splitlines', 'sta swith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'z ll']
Object Lifecycle
[Link]
Object Lifecycle
• Objects are created, used, and discarded
• We have
called special blocks of code (methods) that get
- At the moment of creation (constructor)
- At the moment of destruction (destructor)
• Constructors are used a lot
• Destructors are seldom used
Constructor
e prima purpose of the constructor is to set up
some instance variables to have the proper initial values
when the object is created
class Pa yAnimal:
def __init__(self): $ python pa [Link]
self.x = 0
print('I am constructed') I am constructed
So far 1
def pa y(self) : So far 2
self.x = self.x + 1 I am destructed 2
print('So far',self.x) an contains 42
def __del__(self):
print('I am destructed', self.x)
an = Pa yAnimal() e constructor and destructor
[Link] y() are optional. e constructor is
[Link] y()
an = 42 typically used to set up variables.
print('an contains',an) e destructor is seldom used.
Constructor
In object oriented programming, a constructor in a
class is a special block of statements called when an
object is created
[Link]
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
class Pa yAnimal: Constructors can have
additional parameters.
def __init__(self, z): ese can be used to set up
self.x = 0 instance variables for the
[Link] = z
print([Link],"constructed") pa icular instance of the
class (i.e., for the pa icular
def pa y(self) : object).
self.x = self.x + 1
print([Link],"pa y count",self.x)
s = Pa yAnimal("Sally")
[Link] y()
j = Pa yAnimal("Jim")
[Link] y()
[Link] y() pa [Link]
class Pa yAnimal:
def __init__(self, z):
self.x = 0
[Link] = z
print([Link],"constructed")
def pa y(self) :
self.x = self.x + 1
print([Link],"pa y count",self.x)
s = Pa yAnimal("Sally")
[Link] y()
j = Pa yAnimal("Jim")
[Link] y()
[Link] y()
class Pa yAnimal:
def __init__(self, z):
self.x = 0
s x: 0
[Link] = z
print([Link],"constructed") name:
def pa y(self) :
self.x = self.x + 1
print([Link],"pa y count",self.x)
s = Pa yAnimal("Sally")
[Link] y()
j = Pa yAnimal("Jim")
[Link] y()
[Link] y()
class Pa yAnimal:
def __init__(self, z):
self.x = 0
s x: 0
[Link] = z
print([Link],"constructed") name: Sally
def pa y(self) :
self.x = self.x + 1
print([Link],"pa y count",self.x)
s = Pa yAnimal("Sally")
[Link] y()
j x: 0
j = Pa yAnimal("Jim")
[Link] y() name: Jim
[Link] y()
class Pa yAnimal:
def __init__(self, z): Sally constructed
Sally pa y count 1
self.x = 0 Jim constructed
[Link] = z Jim pa y count 1
print([Link],"constructed") Sally pa y count 2
def pa y(self) :
self.x = self.x + 1
print([Link],"pa y count",self.x)
s = Pa yAnimal("Sally")
[Link] y()
j = Pa yAnimal("Jim")
[Link] y()
[Link] y()
Inheritance
[Link]
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
• e new class (child) has all the capabilities of the old
class (parent) - and then some more
Terminology: Inheritance
‘Subclasses’ are more specialized versions of a class, which
inherit attributes and behaviors from their parent classes, and
can introduce their own.
[Link]
oriented_programming
class Pa yAnimal:
def __init__(self, nam): s = Pa yAnimal("Sally")
self.x = 0 [Link] y()
[Link] = nam
print([Link],"constructed")
j = FootballFan("Jim")
def pa y(self) : [Link] y()
self.x = self.x + 1 [Link]()
print([Link],"pa y count",self.x)
class FootballFan(Pa yAnimal):
def __init__(self, nam) : FootballFan is a class which
super().__init__(nam) extends Pa yAnimal. It has all
[Link] = 0 the capabilities of Pa yAnimal
def touchdown(self):
and more.
[Link] = [Link] + 7 pa [Link]
[Link] y()
print([Link],"points",[Link])
class Pa yAnimal:
def __init__(self, nam): s = Pa yAnimal("Sally")
self.x = 0 [Link] y()
[Link] = nam
print([Link],"constructed")
j = FootballFan("Jim")
def pa y(self) : [Link] y()
self.x = self.x + 1 [Link]()
print([Link],"pa y count",self.x)
class FootballFan(Pa yAnimal): s x:
def __init__(self, nam) :
super().__init__(nam) name: Sally
[Link] = 0
def touchdown(self):
[Link] = [Link] + 7
[Link] y()
print([Link],"points",[Link])
class Pa yAnimal:
def __init__(self, nam): s = Pa yAnimal("Sally")
self.x = 0 [Link] y()
[Link] = nam
print([Link],"constructed")
j = FootballFan("Jim")
def pa y(self) : [Link] y()
self.x = self.x + 1 [Link]()
print([Link],"pa y count",self.x)
class FootballFan(Pa yAnimal): j x:
def __init__(self, nam) :
super().__init__(nam)
[Link] = 0 name: Jim
def touchdown(self):
[Link] = [Link] + 7
[Link] y()
points:
print([Link],"points",[Link])
De nitions
• Class - a template
• Attribute – A variable within a class
• Method - A function within a class
• Object - A pa icular instance of a class
• Constructor – Code that runs when an object is created
• Inheritance - e ability to extend a class to make a new class.
Summa
• Object Oriented programming is a ve structured
approach to code reuse
• We can group data and functionality together and create
many independent instances of a class
Acknowledgements / Contributions
es slide are Copyright 2010- Charles R. Severance ([Link]- ..
[Link]) of the University of Michigan School of Information
and made available under a Creative Commons Attribution 4.0
License. Please maintain this last slide in all copies of the
document to comply with the attribution requirements of the
license. If you make a change, feel free to add your name and
organization to the list of contributors on this page as you
republish the materials.
Initial Development: Charles Severance, University of Michigan
School of Information
… Inse new Contributors here
Additional Source Information
•Snowman Cookie Cutter" by Didriks is licensed under CC BY
[Link] [Link]/photos/dinnerseries/23570475099
•Photo from the television program Lassie. Lassie watches as Je (Tommy Rettig) works on his bike is
Public Domain
[Link]