python 的特殊方法 __str__和__repr__

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__以得到更友好的用户显示。

转载于:https://www.cnblogs.com/zoe233/p/7600853.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值