1. print( 坑的信息 )
坑的编码 |
内容 |
Py023-3 |
__str__ 与 __repr__ 的区别 |
2. 开始填坑
2.1 上例子
>>> class A(object):
... def __str__(self):
... return "this is __str__"
... def __repr__(self):
... return "this is __repr__"
...
>>> a = A()
>>> a
this is __repr__
>>> print(a)
this is __str__
>>>
2.2 关系与区别
- 同时定义
__repr__
方法和 __str__
方法时,print() 方法会调用 __str__
方法
Python 3.7.3 的官方文档
object.__str__(self)
Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.
This method differs from object.__repr__() in that there is no expectation that __str__() return a valid Python expression: a more convenient or concise representation can be used.
The default implementation defined by the built-in type object calls object.__repr__().
- 最后一句大概是说,
__str__
是调用 __repr__
实现的
object.__repr__(self)
Called by the repr() built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an “informal” string representation of instances of that class is required.
This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.
网上看到一个例子,运行了一下
>>> import datetime
>>> today = datetime.datetime.now()
>>> today
datetime.datetime(2019, 4, 11, 20, 45, 8, 463653)
>>> str(today)
'2019-04-11 20:45:08.463653'
>>> repr(today)
'datetime.datetime(2019, 4, 11, 20, 45, 8, 463653)'
>>>
简单地说
-
__str__
表达更简洁,__repr__
显示更全面