python __str__()和__repr__()自定义类的

2022-05-26  本文已影响0人  孙广宁
8.1 我们想修改打印实例时候的输出,这样让输出的结果更具有意义
>>> class Pair:
...     def __init__(self,x,y):
...         self.x =x
...         self.y = y
...     def __repr__(self):
...         return 'Pair({0.x!r},{0.y!r})'.format(self)
...     def __str__(self):
...         return '({0.x!s},{0.y!s})'.format(self)
...
>>> p = Pair(3,4)
>>> p
Pair(3,4)
>>> print(p)
(3,4)
>>>
obj==eveal(repr(obj))
>>> print('p is {0!r}'.format(p))
p is Pair(3,4)
>>> print('p is {0}'.format(p))
p is (3,4)
>>> print('p is {0!s}'.format(p))
p is (3,4)
>>>
上一篇下一篇

猜你喜欢

热点阅读