python - 在这个例子中,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__()
我目前对这段代码的理解:
- 我们有一个 Animal 类,它为每只动物命名为“未命名”
- mouse 和 Goat 类是 Animal 的子类
我不明白的是:
__repr__
,__class__
, 和__name__
各自做 什么- 为什么处理类的东西在变量前后都有下划线?python 是否以不同的方式对待这些对象?还是下划线只是一个表明某些东西的命名方案?
__repr__(self)
函数在做什么
任何帮助表示赞赏!
解决方案
推荐阅读
- jakarta-ee - 创建 JMSProducer 时如何提高性能?
- c - 为什么我的 C 代码在命令提示符下不断返回 0?
- android - 发现多个文件的操作系统独立路径为“META-INF/androidx.localbroadcastmanager_localbroadcastmanager.version”
- python - 为什么键入变量(或表达式)会将值打印到标准输出?
- mysql - 如何使用同一列内的计算
- django - Django:电子邮件未在内置 PasswordResetView 中发送
- c++ - 抛出异常:写访问冲突。p 是 0x1140000
- javascript - 如何将我的 document.write 字符串居中?
- php - 位置实时跟踪项目
- php - 如何在foreach中合并重复项