面向对象编程与tamagotchi类

时间:2014-04-13 03:07:56

标签: python

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

  • teach其中可以有可变数量的字符串输入。这教导了tamagotchi这些话。符号也可以。如果你试图不止一次地教一个tamagotchi相同的单词,它将忽略后来的尝试。

  • play将使tamagotchi返回一个字符串化的单词列表(按顺序)。

  • kill将杀死tamagotchi。一旦tamagotchi在天堂,它不能被教导,并且当你尝试玩它时不会回应。相反,所有进一步的方法调用都将返回字符串"<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()

1 个答案:

答案 0 :(得分:2)

在类方法中传递的self变量引用Tamagotchi的实例。为避免告诉您如何完成作业,请考虑为实例指定名称的__init__函数,所以

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

现在教一个Tamagotchi一个词意味着它应该说新词,前提是它还没有。您在teach方法中有正确的想法,但您没有将其分配给实例,因此在将来的通话中会丢失。同样,对于您的播放方法,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

现在让我们和我的小鸟说话吧。我将这里命名为格拉迪斯。

>>> 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."