目的:改变对象实例的打印或显示输出,让他们更具有可读性
方法:
1、改变__repr__()
内置函数repr()函数返回的字符串和交互式解释器显示的值是一样的。
2、改变__str__()
内置str()函数返回的字符串和str()或print()函数输出显示的值是一样的。
使用场景:
简化调试和实例输出。
注意:
如果__str__()没有被定义,那么会用__repr__()代替输出
举例:
class Article:
def __init__(self, author, datetime):
self.author = author
self.datetime = datetime
def __repr__(self):
return 'Article(%s, %s)' %(self.author, self.datetime)
def __str__(self):
return 'The article was written by %s and published in %s' %(self.author, self.datetime)
在交互式解释器上输出为:
>>>art = Article('ctt', '2021-05-20')
>>>art
Article(ctt, 2021-05-20)
>>>print(art)
The article was written by ctt and published in 2021-05-20
在非交互式解释器上使用(pycharm):debug显示的实例化art和print输出显示的art值一样
art = Article('ctt', '2021-05-20')
print(art)
输出:
The article was written by ctt and published in 2021-05-20