这段代码究竟发生了什么?

时间:2011-05-30 17:50:11

标签: python debugging

我试图重新创建一段基本上是极简主义Tomagatchi的代码。然而,当它被喂食和倾听时,它的“情绪”值不会改变。它仍然“疯狂”。任何帮助将不胜感激!

{#Create name, hunger, boredom attributes. Hunger and Boredom are numberical attributes

class Critter(object):
    def __init__(self, name, hunger = 0, boredom = 0):
        self.name = name
        self.hunger = hunger
        self.boredom = boredom

    #Creating a private attribute that can only be accessed by other methods
    def __pass_time(self):
        self.hunger += 1
        self.boredom += 1

    def __get_mood(self):
        unhappiness = self.hunger + self.boredom
        if unhappiness < 5:
            mood = "happy"
        if 5 <= unhappiness <= 10:
            mood = "okay"
        if 11 <= unhappiness <= 15:
            mood = "frustrated"
        else:
            mood = "mad"
        return mood

    mood = property (__get_mood)

    def talk(self):
        print "Hi! I'm",self.name,"and I feel",self.mood,"now."
        self.__pass_time()

    def eat(self, food = 4):
        print "Brrruuup. Thank you!"
        self.hunger -= food
        if self.hunger < 0:
            self.hunger = 0
        self.__pass_time()

    def play(self, play = 4):
        print "Yaaay!"
        self.boredom -= play
        if self.boredom < 0:
            self.boredom = 0
        self.__pass_time()

    def main ():
        crit_name = raw_input("What do you want to name your critter? ")
        crit = Critter (crit_name)

    choice = None
    while choice != "0":
        print \
              """  0 - Quit
                   1 - Listen to your critter.
                   2 - Feed your critter
                   3 - Play with your critter
              """

        choice = raw_input ("Enter a number: ")

        #exit
        if choice == "0":
            print "GTFO."
        #listen to the critter
        elif choice == "1":
            crit.talk()
        #feed the crit crit critter
        elif choice == "2":
            crit.eat()
        #play with the crit crit critter
        elif choice == "3":
            crit.play()
        #some unknown choice
        else:
            print "\nwat"

    main ()
    raw_input ("\n\nHit enter to GTFO")

2 个答案:

答案 0 :(得分:7)

在_getMood中,应该有elifs。

    if unhappiness < 5:
        mood = "happy"
    elif 5 <= unhappiness <= 10:
        mood = "okay"
    elif 11 <= unhappiness <= 15:
        mood = "frustrated"
    else:
        mood = "mad"

没有他们,实际上只是检查11到15之间是否有不快乐,如果没有,则将心情设定为疯狂。因此从0到10不成功,从16岁开始,一个小动物疯了。

答案 1 :(得分:2)

我想在这样的情况下,替换变量并跟踪代码。

unhappiness = 3

if unhappiness < 5:
    mood = "happy"

好的,我们变得快乐

if 5 <= unhappiness <= 10:
    mood = "okay"

没有发生任何事情,因为3不在5 <= x <= 10

的范围内
if 11 <= unhappiness <= 15:
    mood = "frustrated"

没有任何事情发生,因为3不在11的范围内。 x&lt; 15

else:
    mood = "mad"

其他什么?啊这指的是最后一个条件。所以,如果它不是11&lt; x&lt; 15然后我们生气了。

使用值替换变量,然后逐行跟踪代码,通常应该在这种情况下尝试,至少在它成为第二天性之前。