Skip to content

Problem 2: Cat (100pts)

Problem

Below is a skeleton for the Cat class, which inherits from the Pet class. To complete the implementation, override the __init__ and talk methods and add a new lose_life method, such that its behavior matches the following doctests.

We may change the implementation of Pet while testing your code, so make sure you use inheritance correctly.

下面是 Cat 类的骨架,它继承自 Pet 类。为了完成实现,请覆盖 __init__talk 方法并添加一个新的 lose_life 方法,使其行为与以下 doctests 匹配。

我们在测试您的代码时可能会更改 Pet 的实现,因此请确保您正确使用了继承。

class Pet:
    """A pet.

    >>> kyubey = Pet('Kyubey', 'Incubator')
    >>> kyubey.talk()
    Kyubey
    >>> kyubey.eat('Grief Seed')
    Kyubey ate a Grief Seed!
    """

    def __init__(self, name, owner):
        self.is_alive = True  # It's alive!!!
        self.name = name
        self.owner = owner

    def eat(self, thing):
        print(self.name + " ate a " + str(thing) + "!")

    def talk(self):
        print(self.name)

    def to_str(self):
        "*** YOUR CODE HERE ***"


class Cat(Pet):
    """A cat.

    >>> vanilla = Cat('Vanilla', 'Minazuki Kashou')
    >>> isinstance(vanilla, Pet) # check if vanilla is an instance of Pet.
    True
    >>> vanilla.talk()
    Vanilla says meow!
    >>> vanilla.eat('fish')
    Vanilla ate a fish!
    >>> vanilla.lose_life()
    >>> vanilla.lives
    8
    >>> vanilla.is_alive
    True
    >>> for i in range(8):
    ...     vanilla.lose_life()
    >>> vanilla.lives
    0
    >>> vanilla.is_alive
    False
    >>> vanilla.lose_life()
    Vanilla has no more lives to lose.
    """

    def __init__(self, name, owner, lives=9):
        "*** YOUR CODE HERE ***"

    def talk(self):
        """Print out a cat's greeting."""
        "*** YOUR CODE HERE ***"

    def lose_life(self):
        """Decrements a cat's life by 1. When lives reaches zero, 'is_alive'
        becomes False. If this is called after lives has reached zero, print out
        that the cat has no more lives to lose.
        """
        "*** YOUR CODE HERE ***"

    def to_str(self):
        "*** YOUR CODE HERE ***"

Hints

Hint 1: You can call the __init__ method of Pet to set a cat's name and owner.

Hint 2: The to_str method belongs to Problem 4, you don't need to implement it for the moment.

  • 您可以调用 Pet 的 __init__ 方法来设置猫的名字和主人。

  • to_str 方法属于问题 4,您目前不需要实现它。