class Tamagotchi(object):
def __init__(self,name):
self.name = name
def teach(self,word):
if word == "hello":
return (self.name + "is pining for the fjord")
else:
return (self.name + "says" + word)
def play(self):
return self.teach("and")
这是我的代码
但是我无法获得所需的输出
meow_meow = Tamagotchi("meow meow")
meow_meow.teach("meow")
print(meow_meow.play()) #'meow meow says meow'
meow_meow.teach("purr")
meow_meow.teach("meow")
print(meow_meow.play()) #'meow meow says meow and purr'
print(meow_meow.teach("hello")) #'meow meow is pining for the fjords'
print(meow_meow.play()) #'meow meow is pining for the fjords'
答案 0 :(得分:2)
现在你遇到的几个问题:
'meow meow is pining for the fjords'
是调用meow_meow.kill()
后对每个方法调用的响应,而不仅仅是meow_meow.teach("hello")
。实际上,在您kill
之前,teach("hello")
不应该return
任何。kill
。'meow meow says meow'
是对meow_meow.play()
的回复,不是对meow_meow.teach(...)
的响应,(再次)不应该return
任何内容。teach
是否已知word
,或允许传递多个单词(我认为这是您的标题所指的)。teach
也不会存储Tamagotchi
已经教过的字词。play
教Tamagotchi
单词'and'
,这是无用的 - 它应该通过已经教过的所有单词,'and'
每一个之间。我建议你看看以下内容:
为了指出正确的方向,这是一个开始:
class Tamagotchi(object):
def __init__(self, name):
self.name = name
self.words = []
self.alive = True
答案 1 :(得分:1)
您没有存储word
,您需要:
class Tamagotchi(object):
def __init__(self,name):
self.name = name
self.word = name
def teach(self,word):
self.word = word
return self.say()
def say(self):
if self.word == "hello":
return (self.name + " is pining for the fjord")
else:
return (self.name + " says " + self.word)
def play(self):
return self.teach("and")
注意teach()如何记住这个词。然后说()反刍它。这一次只能用于一个单词。
答案 2 :(得分:-1)
问题是meow_meow.play()等同于meow_meow.teach(x)并且你没有存储教授的单词。所以最简单的方法就是替换
print(meow_meow.play())
用这个:
meow_meow.teach("meow and purr")
您还应该在输出中添加空格。
return (self.name + " says " + word)