Professional Documents
Culture Documents
Object-Oriented Programming
Let’s first informally describe how we would like to use this class
The Python class statement defines a new class (and associated namespace)
Introduction to Computing Using Python
Exercise
def get(self):
'return coordinates of the point as a tuple'
return (self.x, self.y)
def getx(self):
'return x coordinate of the point'
return self.x
Introduction to Computing Using Python
Every object will have its own namespace and therefore its own
instance variables
>>> a = Point()
>>> a.setx(3)
>>> a.sety(4) x y x y
>>> b = Point()
>>> b.setx(0)
>>> b.sety(0)
>>> a.get() object a object b
(3, 4)
>>> b.get()
(0, 0)
>>> a.x 3 4 0 0
3
>>> b.x
0
>>>
Introduction to Computing Using Python
Note: no documentation
Introduction to Computing Using Python
class Point(builtins.object)
| Methods defined here:
|
| get(self)
|
| move(self, dx, dy)
|
| setx(self, xcoord)
|
| sety(self, ycoord)
|
|
----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
Introduction to Computing Using Python
Class documentation
class Point:
'class that represents a point in the plane'
def get(self):
'return coordinates of the point as a tuple'
return (self.x, self.y)
Class documentation
>>> help(Point)
Help on class Point in module __main__:
class Point(builtins.object)
| class that represents a point in the plane
|
| Methods defined here:
|
| get(self)
| return a tuple with x and y coordinates of the point
|
| move(self, dx, dy)
| change the x and y coordinates by dx and dy
|
| setx(self, xcoord)
| set x coordinate of point to xcoord
|
| sety(self, ycoord)
| set y coordinate of point to ycoord
|
|
----------------------------------------------------------------------
| Data descriptors defined here:
...
Introduction to Computing Using Python
Exercise
Develop class Animal that supports methods: >>> snoopy = Animal()
• setSpecies(species) >>> snoopy.setpecies('dog')
>>> snoopy.setLanguage('bark')
• setLanguage(language) >>> snoopy.speak()
• speak() I am a dog and I bark.
class Animal:
'represents an animal'
def speak(self):
'prints a sentence by the animal'
print('I am a {} and I {}.'.format(self.spec, self.lang))
Introduction to Computing Using Python
Overloaded constructor
called by Python each time a Point object is created
class Point:
It takes 3 steps to create a 'class that represents a point in the plane’
Point object at specific x setx(self, xcoord):
__init__(self,
defdef xcoord, ycoord):
and y coordinates 'set x coordinate
'initialize of point
coordinates to xcoord'
to (xcoord, ycoord)'
self.x = xcoord
>>> a = Point() self.y = ycoord
def sety(self, ycoord):
It would
>>> be better if we
a.setx(3)
'set y coordinate
def setx(self, of point to ycoord'
xcoord):
>>> a.sety(4)
could do it in one step
>>> a.get()
self.y
'set = ycoord
x coordinate of point to xcoord'
(3, 4) self.x = xcoord
def get(self):
>>>
'return coordinates
def sety(self, ycoord): of the point as a tuple'
return
'set (self.x, self.y)
y coordinate of point to ycoord'
>>> a = Point(3, 4)
self.y = ycoord
>>> a.get() def move(self, dx, dy):
(3, 4) 'change the x and y coordinates by dx and dy'
def get(self):
>>> self.x += dx
'return coordinates of the point as a tuple'
self.y (self.x,
return += dy self.y)
>>> a
n = Point()
int(3) def get(self):
>>> a.get()
n 'return coordinates of the point as a tuple'
(0,
3 0) return (self.x, self.y)
>>> n = int()
>>> n def move(self, dx, dy):
0 'change the x and y coordinates by dx and dy'
>>> self.x += dx
self.y += dy
Introduction to Computing Using Python
Exercise
Modify the class Animal we developed in the previous section so it supports a
two, one, or no input argument constructor
def speak(self):
'prints a sentence by the animal'
print('I am a {} and I {}.'.format(self.spec, self.lang))
Introduction to Computing Using Python
def getRank(self):
'return rank'
return self.rank
def getSuit(self):
'return suit'
return self.suit
Introduction to Computing Using Python
def __init__(self):
'initialize deck of 52 cards'
self.deck = [] # deck is initially empty
def dealCard(self):
'deal (pop and return) card from the top of the deck'
return self.deck.pop()
def shuffle(self):
'shuffle the deck'
shuffle(self.deck)
Introduction to Computing Using Python
rear
rear rear
rear rear
appts 'Annie' 'Annie'
'John' 'Sandy' 'Sandy'
front
class Queue:
'a classic queue class'
def __init__(self):
'instantiates an empty list'
self.q = []
def isEmpty(self):
'returns True if queue is empty, False otherwise'
return (len(self.q) == 0)
def dequeue(self):
'remove and return item at front of queue'
return self.q.pop(0)
Introduction to Computing Using Python
Python operators
>>> 'he' + 'llo' >>> 'he'.__add__('llo')
'hello' 'hello'
>>> [1,2] + [3,4] >>> [1,2].__add__([3,4])
[1, 2, 3, 4] [1, 2, 3, 4]
>>> 2+4 >>> int(2).__add__(4)
6 6
Class method __add__() implements the behavior of operator + for the class
… it first translates it to … and then evaluates
When Python evaluates
method invocation … the method invocation
object1 + object 2 object1.__add__(object2)
Introduction to Computing Using Python
Operator Method
Overloading repr()
class Point:
def __repr__(self):
'canonical string representation Point(x, y)'
return 'Point({}, {})'.format(self.x, self.y)
Introduction to Computing Using Python
Overloading operator +
>>> a = Point(3,4) >>> a = Point(3,4)
To get this behavior >>> b = Point(1,2) >>> b = Point(1,2)
>>> a+b >>> a.__add__(b)
Point(4, 6) Point(4, 6)
def __repr__(self):
'canonical string representation Point(x, y)'
return 'Point({}, {})'.format(self.x, self.y)
Introduction to Computing Using Python
def isEmpty(self):
return (len(self.q) == 0)
def __len__(self):
return len(self.q)
Introduction to Computing Using Python
Exercise
Modify Deck >>> deck = Deck()
>>> deck.shuffle()
and/or Card to >>> deck.dealCard()
get this behavior Card('2', '♠')
class Card:
'represents a playing card'
str() vs repr()
class Representation(object):
def __repr__(self):
return 'canonical string representation'
def __str__(self):
return 'Pretty string representation.'
Introduction to Computing Using Python
✗
>>> eval(repr(Point(3,5)))
Contract between the constructor Point(3, 5)
>>> Point(3,5) == eval(repr(Point(3,5)))
and operator repr() False
Introduction to Computing Using Python
Overloading operator ==
>>> a = Point(3,5)
For user-defined classes, the >>> b = Point(3,5)
>>> a == b
default behavior for operator == False
is to return True only when the >>> a == a
two objects are the same object. True
For class Point, operator == should return True if the two points have the
same coordinates
class Point:
Exercise
We have already modified class Card to support function repr(). Now
implement
class Card: operator == so two cards with same rank and suit are equal.
'represents a playing card'
def getSuit(self):
__repr__(self):
getRank(self):
'return formal
rank' representation'
suit'
return "Card('{}',
self.suit
self.rank '{}')".format(self.rank, self.suit)
__eq__(self,
__repr__(self):
defdef getSuit(self):other):
'self ==formal
'return other if
suit' rank and suit are the same'
representation'
return self.rank
self.suit =='{}')".format(self.rank,
"Card('{}', other.rank and self.suitself.suit)
== other.suit
Introduction to Computing Using Python
Inheritance
Code reuse is a key software engineering goal
• One benefit of functions is they make it easier to reuse code
• Similarly, organizing code into user-defined classes makes it easier to later
reuse the code
o E.g., classes Card and Deck can be >>> mylst = MyList()
reused in different card game apps >>> mylst.append(2)
>>> mylst.append(3)
>>> mylst.append(5) A MyList
A class can also be reused by extending >>> mylst.append(7) object should
>>> len(mylst) behave just
it through inheritance 4 like a list
>>> mylst.index(5)
2
Example: Suppose that we find it >>> mylst.choice()
7
convenient to have a class that >>> mylst.choice()
3
A MyList
behaves just like the built-in class object should
>>> mylst.choice()
list but also supports a method 3 also support
called choice() that returns an item >>> mylst.choice() method
5 choice()
from the list, chosen uniformly at >>> mylst.choice()
random. 3
Introduction to Computing Using Python
import random
[2,3,5,7]
class MyList(list): object mylst
'a subclass of list that implements method choice'
def choice(self):
'return item from list chosen uniformly at random'
return random.choice(self)
Introduction to Computing Using Python
object is a built-in class with no attributes; it is the class that all classes
inherit from, directly or indirectly
>>> help(object)
Help on class object in module builtins:
class object
| The most base type
A class can also inherit attributes from more than one superclass
class <Class Name>(<Super Class 1>, <Super Class 2>, …):
Introduction to Computing Using Python
For example, a class Bird that supports the same methods class Animal
supports (setSpecies(), setLanguage(), and speak()) but with a
different behavior for method speak()
def speak(self):
'prints a sentence by the animal'
print('I am a {} and I {}.'.format(self.spec, self.lang))
Introduction to Computing Using Python
class Animal
spec lang
Python looks for the definition of an
speak
attribute by starting with the name-
space object
associated
snoopy with object and
Animal
method speak() defined in Bird is used
is used
spec lang
class Super:
'a generic class with one method'
def method(self): # the Super method
print('in Super.method')
class Inheritor(Super):
'class that inherits method'
pass
class Replacer(Super):
'class that overrides method'
def method(self):
print('in Replacer.method')
class Extender(Super):
'class that extends method'
def method(self):
print('starting Extender.method')
Super.method(self) # calling Super method
print('ending Extender.method')
Introduction to Computing Using Python
An encapsulation issue
>>> queue
>>> queue
= Queue()
= Queue()
>>> queue.dequeue()
>>> queue.dequeue()
Traceback
Traceback
(most(most
recent
recent
call call
last):last): We need to be able to
File File
"<pyshell#76>",
"<pyshell#48>",
line line
1, in1,<module>
in <module>
queue.dequeue()
queue.dequeue()
define user-defined
File File
"/Users/me/ch8.py",
"/Users/me/ch8.py",
line line
120, 93,
in dequeue
in dequeue exceptions
raisereturn
EmptyQueueError('dequeue
self.q.pop(0) from empty queue')
EmptyQueueError:
IndexError: pop
dequeue
from from
emptyempty
list queue But first, we need to
learn how to “force” an
What is the problem? exception to be raised
The user of class Queue should not have to know the implementation
detail that a list stores the items in a Queue object
Raising an exception
>>> while True:
By typing Ctrl-C, a user can pass
force a KeyboardInterrupt
Traceback (most recent call last):
exception to be raised File "<pyshell#53>", line 2, in <module>
pass
KeyboardInterrupt
Any exception can be raised >>> raise ValueError()
Traceback (most recent call last):
within a program with the File "<pyshell#54>", line 1, in <module>
raise statement raise ValueError()
ValueError
• ValueError, like all >>> raise ValueError('Just joking...')
exception types, is a class Traceback (most recent call last):
File "<pyshell#55>", line 1, in <module>
• ValueError() uses the raise ValueError('Just joking...')
default constructor to create ValueError: Just joking...
an exception (object) >>> try:
raise ValueError()
• statement raise switches except:
control flow from normal to print('Caught exception.')
exceptional
• The constructor can take a
Caught exception.
“message” argument to be >>>
stored in the exception object
Introduction to Computing Using Python
User-defined exceptions
Every built-in exception >>>
>>> help(Exception)
class MyError(Exception):
Help pass
on class Exception in module builtins:
type is a subclass of class
Exception. class Exception(BaseException)
>>> raise MyError('Message in a bottle')
| Common base recent
Traceback (most class for all
call non-exit exceptions.
last):
|File "<pyshell#71>", line 1, in <module>
| raise
MethodMyError('Message
resolution order:in a bottle')
A new exception class |
MyError: Exception
Message in a bottle
should be a subclass, either |
>>> BaseException
directly or indirectly, of | object
. . .
Exception.
Introduction to Computing Using Python