Skip to main content
 首页 » 编程设计

python之使用电子鸡类的面向对象编程

2024年11月01日8kenshinobiy

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

  • teach其中可以有可变数量的字符串输入。这教电子鸡这些话。符号也将起作用。如果您多次尝试教电子鸡相同的单词,它会忽略后面的尝试。

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

  • kill会杀死电子鸡。一旦电子鸡进入天堂,它就无法被教导,并且在您尝试与它玩耍时也不会做出任何反应。相反,所有进一步的方法调用将返回字符串 "<name> is pining for the fjords"其中 <name>是电子鸡的名字。

这是我的代码:

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