[Tutor] Passing perimeters in dictionary values?
Andre Engels
andreengels at gmail.com
Wed Feb 25 09:21:47 CET 2009
On Wed, Feb 25, 2009 at 2:32 AM, nathan virgil <sdragon1984 at gmail.com> wrote:
> Erm, it's still not working...
>
> Whenever I try to use the talk method (which reports the mood, and doesn't
> take parameters), it says I gave it too many parameters. Maybe it might help
> if I posted the code in it's entirety....
>
>
> # Critter Caretaker
> # A virtual pet to care for
>
> class Critter(object):
> """A virtual pet"""
> def __init__(self, name, hunger = 0, boredom = 0):
> self.name = name
> self.hunger = hunger
> self.boredom = boredom
>
> def __pass_time(self):
> self.hunger += 1
> self.boredom += 1
>
> def __get_mood(self):
> unhappiness = self.hunger + self.boredom
> if unhappiness < 5:
> mood = "happy"
> elif 5 <= unhappiness <= 10:
> mood = "okay"
> elif 11 <= unhappiness <= 15:
> mood = "frustrated"
> else:
> mood = "mad"
> return mood
>
> mood = property(__get_mood)
>
> def talk(self):
> print "I'm", self.name, "and I feel", self.mood, "now.\n"
> self.__pass_time()
>
> def eat(self, food = 4):
> print "Brruppp. Thank you."
> self.hunger -= food
> if self.hunger < 0:
> self.hunger = 0
> self.__pass_time()
>
> def play(self, fun = 4):
> print "Wheee!"
> self.boredom -= fun
> if self.boredom < 0:
> self.boredom = 0
> self.__pass_time()
>
> def backdoor(self):
> print "hunger:", self.hunger, "boredom:", self.boredom
>
> def quit():
> print "God-bye!"
>
>
> def main():
> crit_name = raw_input("What do you want to name your critter?: ")
> crit = Critter(crit_name)
>
> selection = None
> while selection != "0":
> print \
> """
> Critter Caretaker
>
> 0 - Quit
> 1 - Listen to your critter
> 2 - Feed your critter
> 3 - Play with your critter
> """
>
> selection = raw_input("Choice: ")
> choices = {"0":(quit, None), "1":(crit.talk, None), "2":(crit.eat,
> 3), "3":(crit.play, 3), "Xyzzy":(crit.backdoor, None)}
> if selection in choices:
> choice = choices[selection]
> choice[0](choice[1])
Yes, that won't work - you are now calling 'quit' and 'talk' with the
argument 'None' rather than without an argument. One way to resolve
this would be to use my proposal: take out the "None"s (but keep the
comma before it) and chance this line to
choice[0](*choice[1:])
which also has the advantage of still working with more than one argument
Another would be to not change the definition of choices, but replace
choice[0](choice[1])
by:
if not choice[1] is None:
choice[0](choice[1])
--
André Engels, andreengels at gmail.com
More information about the Tutor
mailing list