首页 > 解决方案 > 在这个例子中,self.__class__、__name__ 和 __repr__ 的目的是什么?

问题描述

我是 python 的新手(和一般的编码),我一直在努力将我的头脑围绕类。我觉得类的概念刚刚开始为我所用,但是在混合中添加子类(与元类是一样的吗???)让我更加困惑。

在我朋友的推荐下,我一直在努力完成 python zoo 项目。目标是使用类和面向对象的编程来创建一个程序,该程序可以表示有笼子的动物园,里面有动物,这些动物具有独特的属性。(如果你想看的话,这里是练习,但我会提供与我的困惑相关的代码https://github.com/gabits/zoo_exercise

class Animal:
    """ Can be placed inside cages, and according to its place in food chain
    it has a list attribute of its prey (what it likes to eat).
    """

    prey = []

    def __init__(self):
        self.name = 'Unnamed'       # Default naming, to be modified

    def __repr__(self):
        """ Identifies the Animal by its name and species (subclass).
        """
        species = self.__class__.__name__
        return self.name + " " + species if self.name != 'Unnamed' else species


class Mouse(Animal):

    def __init__(self):
        super().__init__()


class Goat(Animal):

    def __init__(self):
        super().__init__()

我目前对这段代码的理解:

我不明白的是:

任何帮助表示赞赏!

标签: pythonpython-3.xsubclass

解决方案


推荐阅读