Python中的类错误

时间:2014-04-25 08:21:20

标签: python

以下是测试用例,之后是我的代码

我需要的是纠正我在self.teach中的错误。在下面的测试用例中,我的代码说“喵喵叫meowpurr”,正确的是“喵喵说喵喵和呜呜”。 其他测试用例都是正确的。

     #test cases    
meow_meow = Tamagotchi("meow meow")
meow_meow.teach("meow")
meow_meow.play()
>>>>"meow meow says meow"
meow_meow.teach("purr")
meow_meow.teach("meow")
meow_meow.play()
>>>>'meow meow says meow and purr'  #My own code state " meow meow says meowpurr" 

使用我的代码:

class Tamagotchi(object):
    def __init__(self, name):
        self.name = name
        self.words = str(self.name) + " says "
        #check alive, dead within all the methods
        self.alive = True

   #trouble portion
   def teach(self, *words):
        if self.alive == False:
            self.words = self.name + " is pining for the fjords"
            return self.words
        else:
            listing = []
            for word in words:
                listing.append(str(word))
            B = " and ".join(listing)
            self.words += B


    def play(self):
        return self.words
    def kill(self):
        if self.alive == True:
            self.words = self.name + " is pining for the fjords"
            self.alive = False
            return self.name + " killed"
        else:
            return self.name + " is pining for the fjords"

由于

1 个答案:

答案 0 :(得分:2)

不要将words存储为字符串;将其存储为列表,仅在运行' and '时加入.play()列表;这也是你测试你的电子宠物还活着的地方:

class Tamagotchi(object):
    def __init__(self, name):
        self.name = name
        self.words = []
        self.alive = True

    def teach(self, *words):
        self.words.extend(words)    

    def kill(self):
        self.alive = False

    def play(self):
        if self.alive:
            return '{} says {}'.format(self.name, ' and '.join(self.words))
        else:
            return '{} is pining for the fjords'.format(self.name)

您的测试用例似乎不需要Tamagotchi.teach()Tamagotchi.kill()来返回任何内容。