1.类的实例化返回值

1 class Foo(object):
2     def __init__(self):
3         pass
4 
5 obj=Foo()
6 print(obj)
View Code

返回值:<__main__.Foo object at 0x0000000001E9AE48>

 

2.__str__方法:

1 class Foo(object):
2     def __init__(self):
3         pass
4 
5     def __str__(self):
6         return "123"
7 
8 obj=Foo()
9 print(obj)
View Code

返回值:123

 

3.__repr__方法:

 1 class Foo(object):
 2     def __init__(self):
 3         pass
 4 
 5     # def __str__(self):
 6     #     return "123"
 7 
 8     def __repr__(self):
 9         return 'this is repr'
10 
11 obj=Foo()
12 
13 print(obj)
View Code

返回值:this is repr

 

4.__str__方法 和 __repr__方法:

 1 class Foo(object):
 2     def __init__(self):
 3         pass
 4 
 5     def __str__(self):
 6         return "this is str"
 7 
 8     def __repr__(self):
 9         return 'this is repr'
10 
11 obj=Foo()
12 
13 print(obj)
View Code

返回值:this is str

__str__的优先级高于__repr__

 

总结:

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

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

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

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

posted on 2017-09-27 11:55  Zoe233  阅读(375)  评论(0编辑  收藏  举报