prev | Version 1107 (Mon Nov 27 20:46:03 2006) | next |
for time in simulation_period: for thing in world: if type(thing) is plant: update_plant(thing, time) elif type(thing) is fish: update_fish(thing, time) elif type(thing) is creepy_crawly: update_creepy_crawly(thing, time) # marker:main:vdots
for time in simulation_period: for thing in world: thing.update(time)
Figure 14.1: Memory Model for Classes and Objects
class
keywordobject
in parentheses":"
and an indented block containing the class's contentsclass Empty(object): pass
pass
means “do nothing”, i.e., create an empty classif __name__ == '__main__': first = Empty() second = Empty() print 'first has id', id(first) print 'second has id', id(second)
first has id 5086860 second has id 5086892
id
returns the object's hash codeif __name__ == '__main__':
self
this
in C++ and Java, the name is just a conventionobject.method(argument)
is equivalent to:C
that object
is an instance ofC.method(object, argument)
class Greeting(object): def say(self, name): print 'Hello, %s!' % name if __name__ == '__main__': greet = Greeting() greet.say('object')
Hello, object!
self.x = 3
x
with the value 3x
with the value 3class Point(object): def set_values(self, x, y): self.x = x self.y = y def get_values(self): return (self.x, self.y) def norm(self): return math.sqrt(self.x ** 2 + self.y ** 2) if __name__ == '__main__': p = Point() p.set_values(1.2, 3.5) print 'p is', p.get_values() print 'norm is', p.norm()
p is (1.2, 3.5) norm is 3.7
Figure 14.2: Creating a Simple Point
p = Point() p.x = 3.5 p.y = 4.25 print 'point is', p.get_values()
point is (3.5, 4.25)
__init__
, Python will call it when building new instancesclass Point(object): def __init__(self, x=0, y=0): self.reset(x, y) def reset(self, x, y): assert (type(x) is int) and (x >= 0), 'x is not non-negative integer' assert (type(y) is int) and (y >= 0), 'y is not non-negative integer' self.x = x self.y = y def get(self): return (self.x, self.y) def norm(self): return math.sqrt(self.x ** 2 + self.y ** 2) if __name__ == '__main__': p = Point(1, 1) print 'point is initially', p.get() p.reset(1, 1) print 'p moved to', p.get()
point is initially (1, 1) p moved to (1, 1)
__init__
is just one example of a special method__str__
__str__
if it exists, orclass Point(object): &vdots; def __str__(self): return '(%4.2f, %4.2f)' % (self.x, self.y) if __name__ == '__main__': p = Point(3, 4) print 'point is', p
point is (3, 4)
Organism
that represents living thingsMammal
Organism
's definition and add more members and methodsclass Organism(object): def __init__(self, common_name, sci_name): self.common_name = common_name self.sci_name = sci_name def get_common_name(self): return self.common_name def get_sci_name(self): return self.sci_name def __str__(self): return '%s (%s)' % (self.common_name, self.sci_name) class Mammal(Organism): def __init__(self, common_name, sci_name, body_temp, gest_period): Organism.__init__(self, common_name, sci_name) self.body_temp = body_temp self.gest_period = gest_period def get_body_temp(self): return self.body_temp def get_gest_period(self): return self.gest_period def __str__(self): extra = ' %4.2f degrees / %d days' % (self.body_temp, self.gest_period) return Organism.__str__(self) + extra if __name__ == '__main__': creature = Mammal('wolf', 'canis lupus', 38.7, 63) print creature
wolf (canis lupus) 38.70 degrees / 63 days
Figure 14.3: Memory Model for Inheritance
Mammal
's constructor calls Organism
's to initialize the organism-ish bits of the objectMammal
defines its own __str__
methodOrganism
Mammal.__str__
calls Organism.__str__
for the same reason that Mammal.__init__
calls Organism.__init__
Bird
from Organism
class Bird(Organism): def __init__(self, common_name, sci_name, incubate_period): Organism.__init__(self, common_name, sci_name) self.incubate_period = incubate_period def get_incubate_period(self): return self.incubate_period def __str__(self): extra = ' %d days' % self.incubate_period return Organism.__str__(self) + extra if __name__ == '__main__': creatures = [ Bird('loon', 'gavia immer', 27), Mammal('grizzly bear', 'ursus arctos horribilis', 38.0, 210) ] for c in creatures: print c
loon (gavia immer) 27 days grizzly bear (ursus arctos horribilis) 38.00 degrees / 210 days
class Mineral(object): def __init__(self, common_name, sci_name, formula): self.common_name = common_name self.sci_name = sci_name self.formula = formula def get_common_name(self): return self.common_name def get_sci_name(self): return self.sci_name def __str__(self): return '%s/%s: %s' % (self.common_name, self.sci_name, self.formula) if __name__ == '__main__': things = [ Mammal('arctic hare', 'Lepus arcticus', 40.1, 50), Mineral("fool's gold", 'iron pyrite', 'FeS2') ] for t in things: print t.get_common_name(), 'is', t.get_sci_name()
arctic hare is Lepus arcticus fool's gold is iron pyrite
Child.meth
may ignore some of Parent.meth
's pre-conditions, but may not impose moreChild.meth
accepts everything thatParent.meth
did, and possibly moreParent.meth
correctly is guaranteed to call Child.meth
correctly tooChild.meth
must satisfy all the post-conditions of Parent.meth
, and may impose moreChild.meth
's possible output is a subset of Parent.meth
'sParent.meth
will still work if given an instance of Child
insteadPlant
and Animal
from Organism
Organism
two methods: can_move
and move
Plant.can_move()
returns False
Plant.move()
raises an exceptionOrganism
one method: move
Plant.move()
does nothingPlant.move
implies that plants can do something they can'tFigure 14.4: CRC Cards
prev | Copyright © 2005-06 Python Software Foundation. | next |