下面是测试用例,后面是我的代码
我需要纠正的是我在 self.teach 中的错误。在下面的测试用例中,我的代码是“喵喵说喵喵”,而正确的是“喵喵说喵喵和咕噜声”。 其他测试用例都是正确的。
#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"
谢谢
请您参考如下方法:
不要将 words 存储为字符串;而是将其存储为列表,并且仅在运行 .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() 来返回任何内容。
