手记

python __repr__ __str__的区别

类的订制

两者都是用来实现类的订制

__repr__ 在使用内建函数 repr()进自动调用

__str__ 在使用print()进自动调用

好的习惯把这两个定制方法进行重写,从而在输出显示时更方便

In [17]: 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)
    ...:

In [18]: p = Pair(3,4)

In [19]: p
Out[19]: Pair(3, 4)

In [20]: repr(p)
Out[20]: 'Pair(3, 4)'

0人推荐
随时随地看视频
慕课网APP