综述

Python 定义了 __str__()__repr__() 两种方法,__str__() 用于显示给用户,而 __repr__() 用于显示给开发人员。


Python中这个 _repr_ 函数,对应 repr(object) 这个函数,返回一个可以用来表示对象的可打印字符串:

  1. 尝试生成这样一个字符串,将其传给 eval() 可重新生成同样的对象 ;

  2. 否则,生成用尖括号包住的字符串,包含类型名和额外的信息(比如地址) ;

  3. 一个类(class)可以通过 __repr__() 成员来控制repr()函数作用在其实例上时的行为。


## 例子
  1. 当一个类没有定义 __str__()__repr__() 时,直接在命令行中输入这个类的示例以及打印示例,生成用尖括号包住的字符串,包含类型名和额外的信息(比如地址):
1
2
3
4
5
6
7
8
>>> class A():
... pass
...
>>> a = A()
>>> a
<__main__.A object at 0x108b59320>
>>> print(a)
<__main__.A object at 0x108b59320>
  1. 当一个类定义了 __str__() ,没有定义 __repr__() 时,直接在命令行中输入这个类的示例以及打印示例:
1
2
3
4
5
6
7
8
9
>>> class B():
... def __str__(self):
... return 'B'
...
>>> b = B()
>>> b
<__main__.B object at 0x108b59358>
>>> print(b)
B
  1. 当一个类定义了 __repr__() ,没有定义 __str__() 时,直接在命令行中输入这个类的示例以及打印示例:
1
2
3
4
5
6
7
8
9
>>> class C():
... def __repr__(self):
... return 'c'
...
>>> c = C()
>>> c
c
>>> print(c)
c

虽然没有定义 __str__(), 但是两种方法都能打印出 c

  1. 同时定义了两者:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> class D():
... def __str__(self):
... return '__str__ d'
... def __repr__(self):
... return '__repr__ d'
...
>>> d = D():
File "<stdin>", line 1
d = D():
^
SyntaxError: invalid syntax
>>> d = D()
>>> d
__repr__ d
>>> print(d)
__str__ d

定义方法

  1. 有一个偷懒的定义repr的方法:
1
2
3
4
5
6
7
8
9
10
>>> class Person(object):
... def __str__(self):
... return 'Person'
... __repr__ = __str__
...
>>> p = Person()
>>> p
Person
>>> print(p)
Person
  1. 另一种方式:
1
2
3
4
5
6
7
8
9
10
11
>>> class ListStack:
... def __str__(self):
... return 'ListStack'
... def __repr__(self):
... return str(self)
...
>>> l = ListStack()
>>> l
ListStack
>>> print(l)
ListStack

但若是没有定义 __str__()

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> class E():
... def __repr__(self):
... return str(self)
...
>>> e = E()
>>> e
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __repr__
File "<stdin>", line 3, in __repr__
File "<stdin>", line 3, in __repr__
[Previous line repeated 196 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object