[Tutor] Critter

Alan Gauld alan.gauld at btinternet.com
Mon Jun 27 10:10:02 CEST 2011


"Vincent Balmori" <vincentbalmori at yahoo.com> wrote

> I'm on the Critter Caretake problem that involves handling more than 
> one
> critter. I have looked At David Merrick's threads for some answers,

Given that David hasn't solved the problem yet that may not
be the best source! :-)

> difference is that he created a whole new class to handle it,

He has now reverted to a simple list.

> made more critter objects. The only problem I have left is to have 
> my
> actions (play and eat) apply to all my creatures ALL AT ONCE, 
> instead of one
> at a time like it is in my code right now.

You can't. You can only apply the methods to one critter at a time.
You can write code to wrap it all up into a convenient single call,
but that code will still need to call each item separately. There is
no such thing as a "call all" mechanism in Python.

BTW, You have the same issue as David with __str__.
__str__() should return a string, it should not print anything itself.
If you sdo that you can then, in your main code write

print(crit1)

instead of

crit1.__str__()

This makes using objects much more like using other data types.

Also in your init method:

    def __init__(self, name, hunger = 0, boredom = 0):
        hunger = random.randint(0,15)
        boredom = random.randint(0,15)

These two lines mean you throw away the values being
passed in to the constructor, so you might as well not
have them. And...

        self.name = name
        self.hunger = hunger
        self.boredom = boredom

Since you just assign them to the attributes you might as well
just do the call to randint() here and delete the first two lines
completely.

Finally in play()

    def play(self, fun = 4):
        while self.boredom >= 3:
            fun = int(input("\n How long do you want to play?: "))
            if fun > 5:
                int(input("\n How long do you want to play?: "))

You ignore the value of fun passed into the method.
(And in your code never pass a value) So again you could
just lose the fun parameter.

Then if fun > 5 you ask the user for a value, convert it to an
int then throw it away so it does no good. You probably should
assign the new value to fun.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list