[Tutor] OO approach to solving problem?
Bob Gailer
ramrom@earthling.net
Tue Jan 7 19:50:03 2003
--=======39424E94=======
Content-Type: text/plain; x-avg-checked=avg-ok-6F772678; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit
At 02:32 PM 1/7/2003 -0700, Brad Reisfeld wrote:
>As a simple example of what I am trying to do, imagine a collection of
>creatures that you would like to 'manage'. Each creature has a certain rate
>of growth, a certain probability of transforming into another creature at
>some point in time, and a given lifetime. You would like to keep an
>'inventory' of the creatures as a function of time.
>
>In terms of programming, it seems to me that one approach might be to have
>each creature as an instance of a creature class with properties like type
>of creature, growth rate, lifetime, transformation probability, and age.
>These instances would be created by a 'master class' (a factory class?) that
>would 'create' each creature, update it as to its age, and transform it. At
>some point, the instance would 'alert' the master class that it is ready to
>die and the master class would delete it.
Whoa. Classes don't do things. Module statements run the show, and they in
turn can call functions, create instances of classes, and invoke instance
methods. Statements in functions and methods continue to run the show.
Potential solution outline:
class Creature:
def __init__(self, ctype, growth_rate, probability, lifetime):
self.ctype = ctype
self.growth_rate = growth_rate
self.probability = probability
self.lifetime = lifetime
self.age = 0
self.alive = 1
def grow(self):
self.age += 1
self.alive = self.lifetime > self.age
if self.alive:
# transform ??
return self.alive
if __name__ == '__main__':
collection = []
for creature_number in range(100000): # create the creature collection
# determine ctype, growth_rate, probability, lifetime for next creature
collection.append(Creature(ctype, growth_rate, probability, lifetime))
for timestep in range(1000000):
collection = [creature in collection for creature.grow()] # age each
creature and retain just those that still live
On a 1 Ghz Win2K 512 K Ram machine with collection size = 4 and 10*6 cycles
last loop required about 30 seconds. For about 100 creatures and 10*5
cycles about same time. YMMV.
Other approaches that might be faster would involve just some arrays of
data and no instance objects.
HTH
Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=======39424E94=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-6F772678
Content-Disposition: inline
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002
--=======39424E94=======--