gpt4 book ai didi

python - Python 错误中的类

转载 作者:太空宇宙 更新时间:2023-11-04 03:46:59 24 4
gpt4 key购买 nike

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

我需要纠正的是我在 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() 来返回任何内容。

关于python - Python 错误中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23287844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com