__str__, __repr__


In [1]: class Test(object): 
   ...:     def __init__(self, value='hello, world!'): 
   ...:         self.data = value 
   ...:                                                                   

In [2]: t = Test                                                          

In [3]: t = Test()                                                        

In [4]: t                                                                 
Out[4]: <__main__.Test at 0x7fdbe0213940>

In [5]: print(t)                                                          
<__main__.Test object at 0x7fdbe0213940>

In [6]: class TestRepr(Test): 
   ...:     def __repr__(self): 
   ...:         return 'TestRepr(%s)' % self.data 
   ...:                                                                   

In [7]: tr = TestRepr()                                                   

In [8]: tr                                                                
Out[8]: TestRepr(hello, world!)

In [9]: print(tr)                                                         
TestRepr(hello, world!)

In [10]: class TestStr(Test): 
    ...:     def __str__(self): 
    ...:         return '[Value:%s]' % self.data 
    ...:          
    ...:                                                                  

In [11]: ts = TestStr()                                                   

In [12]: ts                                                               
Out[12]: <__main__.TestStr at 0x7fdbe1c49ef0>

In [13]: print(ts)                                                        
[Value:hello, world!]

1

__repr__和__str__这两个方法都是用于显示的,__str__是面向用户的,而__repr__面向程序员。

打印操作会首先尝试__str__和str内置函数(print运行的内部等价形式),它通常应该返回一个友好的显示。

repr__用于所有其他的环境中:用于交互模式下提示回应以及repr函数,如果没有使用__str,会使用print和str。它通常应该返回一个编码字符串,可以用来重新创建对象,或者给开发者详细的显示。

当我们想所有环境下都统一显示的话,可以重构__repr__方法;当我们想在不同环境下支持不同的显示,例如终端用户显示使用__str__,而程序员在开发期间则使用底层的__repr__来显示,实际上__str__只是覆盖了__repr__以得到更友好的用户显示。

猜你喜欢

转载自blog.csdn.net/vivian_wanjin/article/details/83928455