目录
例子
关系
使用
官方文档
参考
__repr__ 和 __str__ 是 Python 的两个魔法方法(Magic/Special method),更多魔法方法可以参考 A Guide to Python's Magic Methods 以及 Special method names。
提前说明下面的 str() 和 repr() 都是 Python 中的内置函数,分别调用 __str__() 和 __repr__()。至于内置函数的源码实现可以参考 Finding the source code for built-in Python functions?。
例子
>>> class A:
pass
>>> a1 = A()
>>> print(repr(a1))
>>> print(str(a1))
这里的 0x0000000003166EB8 是什么呢?我们可以用 hex(id(a1)) 方法验证一下,发现结果和它是相同的。说明这就是 a1 对象的 id。更具体一点:
CPython implementation detail: For CPython, id(x) is the memory address where x is stored.
可以参考:In Python, what does '' mean?
>>> class A:
def __str__(self):
#__str__使用:被打印的时候需要以字符串的形式输出的时候,就会找到这个方法,并将返回值打印出来
retu