Q and A for Sections 6.2, 6.3 Victor Norman CS106

advertisement
Q and A for Sections 6.2, 6.3
Victor Norman
CS106
Parameterized Constructor
Q: Can you create multiple constructors for a class,
so that you can create new objects in different
ways?
A: No. You can have only 1 __init__ definition.
But you can use optional parameters to allow the
caller to create objects in multiple ways.
Remember: in general, a constructor should
initialize all its member attributes to values.
Example
class Card:
def __init__(self, num=2, suit=“H”):
“””Create new card. If num and suit are
not specified, it is a 2 of hearts.”””
self._num = num
self._suit = suit
card = Card()
card2 = Card(11, “S”)
# 2 of hearts
# jack of spades
Exercise
Given this definition, write the accessor and
mutator methods.
class Car:
def __init__(self, numWheels=4, color=“black”):
self._numWh = numWheels
self._color = color
How does __str__ get called?
• Special methods get called by the python interpreter
when they are defined in a class.
• e.g., __str__(), if defined, is called by python
whenever the object must be converted to a string –
like when str(obj) is called or print obj is called.
• in other words: the python interpret sees this: print
obj.
– It looks up the class of obj, and checks if __str__ has
been defined for it. If so, it calls it to get the string
representation for it. Otherwise, it calls a built-in way to
convert it – usually resulting in something like
<__main__.Obj instance at 0x1007a4098>
What other special methods are
there?
• https://docs.python.org/2/reference/datamo
del.html
• Especially useful:
__cmp__(self, other): compare two objects
__contains__(self, item): called when in is used
__add__, __sub__, __mul__, etc.:
x + y  x.__add__(y), based on x’s type.
Which special methods must we
know?
__init__
__str__
__cmp__
(others, like __add__, are occasionally useful…)
NOTE NOTE NOTE: do *not* define your own
methods with __ before and after.
Polymorphism
• Means: operators/functions (like +, -, abs(),
len(), in, and, +=, %) may behave completely
differently, based on the types of their
operands.
• Also known as “operator overloading”
• “Josh ” + “Bulten”  concatenation
• 1 + 4
 addition
• [‘Go’] + [‘Calvin’]  append
jumpPrevChannel() code
• Television class has two attributes: _channel,
_prevChan.
• Wrong:
self._channel = self._prevChan
self._prevChan = self._channel
• Need to swap values: easiest with tuple
assignment:
self._channel, self._prevChan =
self._prevChan, self._channel
isinstance()
• returns boolean
• Very useful for checking types of input
parameters to a function/method
• isinstance(object, (tuple, of, types))

boolean
• if not isinstance(param, (int, float)):
print “Illegal parameter!”
• (We’ll learn how to handle this better next
week, with exceptions.)
Objects that reference other objects
• Very common to have multiple classes, and
objects in one class reference other classes.
• E.g.: deck object has a list of card objects.
– Always want to store objects – not, e.g., string
representations of objects.
• Important to get the methods in the correct
classes.
Calling methods from methods
Q: Is calling a method within a method
definition similar to calling a function from
within another function?
A: Yes and no.
Yes: control is transferred to the method and
returned back when the method completes.
No: you have to use self.calledMethod() to do
the call.
Example
class Hand:
def __init__(self, ……):
…
def isStraight(self):
…
def isFlush(self):
…
def isStraightFlush(self):
‘’’return True if this hand is a
straight flush, False otherwise.’’’
return self.isFlush() and self.isStraight()
Two-dimensional arrays/lists
• Often in modeling the world, we need to use
two-dimensional arrays of “cells”.
• We can model many different things with 2d
arrays:
– landscapes
– petri dishes
– mini-world
– matrix
• store as a list of lists.
2D lists
• Like putting turtles on the screen, the 2d array
has a width and height.
• Typically x is horiz, y is vertical. Often (0, 0) is
upper-left corner.
• If world is your 2d list, then we access by
world[x][y]
• x is column index, y is row index (or, y is the item
in the y-th row in the x-th column)
• world[x] is a column.
Initializing a 2D list (list of lists)
• Want MAXCOLS columns and MAXROWS rows, each holding subsequent
integers from 0.
– for 3x4 array:
world = [ [0, 1, 2, 3], [4, 5, 6, 7],
[8, 9, 10, 11] ]
MAXROWS = 3
MAXCOLS = 4
world = []
for x in range(MAXCOLS): # create MAXCOLS lists
world.append([])
val = 0
for col in world: # add MAXROWS items to each column
for y in range(MAXROWS):
col.append(val)
val += 1
Exercise: average neighbors
• Write code to find the sum of 4 neighbors of
cell at x, y, assuming cell is not on an edge.
sum = world[x-1][y] + world[x+1][y] +
world[x][y-1] + world[x][y+1]
Example: Teams, Players
Write a class definition for a Player class.
Each Player object has these attributes:
•
•
•
•
•
•
_name
_number
_age
_position
_salary
_team
Write the constructor definition.
Continued
Write a class definition for a Team.
Each Team object contains
•
•
•
•
•
_name
_players
addPlayer()
delPlayer()
getTotalSalary()
Write the constructor (setting name and players).
Write addPlayer().
Continued
Want to be able to print out this for a player:
Peyton Manning, #18, QB, Denver
Write the code to do this.
Continued
Write the code for getTotalSalary() in Team.
Download