编写一个类Tamagotchi,该类创建具有指定名称的Tamagotchi对象。您应该确定Tamagotchi对象应具有哪些属性,以支持所需的行为,如下所述。一个Tamagotchi对象t具有三种方法:


teach其中可以有可变数量的字符串输入。这教导了他妈哥池这些话。符号也将起作用。如果您尝试不止一次地教一个tamagotchi相同的单词,它将忽略以后的尝试。
play将使tamagotchi返回已教过的单词的字符串列表(按顺序排列)。
kill将杀死他妈哥池。一旦他妈哥池进入天堂,当您尝试玩它时就不会被教导并且不会做出反应。取而代之的是,所有其他方法调用都将返回字符串"<name> is pining for the fjords",其中<name>是tamagotchi的名称。


这是我的代码:

class Tamagotchi():
    def __init__(self, name):
        self.name = name

    def teach(self, words):
        new_words = []
        [new_words.append(x) for x in words if x not in new_words]
        ("".join(new_words))

    def play(self):
        return 'meow meow says ' + Tamogotchi.teach(words)


测试代码:

>>> 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'
>>> meow_meow.kill()
'meow_meow killed'
>>> meow_meow.teach("hello")
'meow meow is pining for the fjords'
>>> meow_meow.play()
'meow meow is pining for the fjords'


我的代码有什么问题?我没有得到想要的meow_meow.play()结果

最佳答案

在类方法中传递的self变量引用Tamagotchi的实例。为避免告诉您如何做功课,请考虑在__init__函数中为实例分配名称,因此

>>> meow_meow = Tamagotchi("meow meow")
>>> meow_meow.name
'meow meow'


现在教一个Tamagotchi单词意味着它应该说出新单词,前提是它还不存在。您在teach方法中有一个正确的想法,但是您没有将其分配给该实例,因此在以后的调用中会丢失它。同样,对于您的play方法,在该方法中未定义words,因此它将失败。考虑在teach中跟踪单词,然后在play中对其进行格式化。

编辑:
由于OP表示这太含糊。本示例将使用一只鹦鹉。我的鹦鹉虽然很笨,但他只重复我说的最后一句话,所以让我们在代码中实现我的鹦鹉

class Parrot():
    def __init__(self, name):
        # self is passed implicitly for new instances of the class
        # it refers to the instance itself
        self.name = name
        self.words = ""

    def hear(self, words):
        # My parrot overhears me saying a sentence
        # 'self', the first argument passed, refers to the instance of my parrot
        # I overwrite the instance value of 'words' (self.words) by assigning the
        # new words that were passed as the instance words value
        self.words = words

    def speak(self):
        # I return whatever the instance 'words' variable contains
        return self.words


现在让我进行一次我和我的鸟儿交谈的过程。我在这里命名为Gladys。

>>> my_parrot = Parrot("Gladys")
>>> my_parrot.speak()
""
>>> my_parrot.hear("Gladys, what is your name?")
>>> my_parrot.speak()
"Gladys, what is your name?"
>>> my_parrot.hear("No, Gladys, what is your name?")
>>> my_parrot.speak()
"No, Gladys, what is your name?"
>>> my_parrot.hear("No, you are Gladys.")
>>> my_parrot.speak()
"No, you are Gladys."

10-06 00:48