Python中__repr__和__str__区别详解
作者:我爱学python 时间:2022-02-17 04:45:25
看下面的例子就明白了
class Test(object):
def __init__(self, value='hello, world!'):
self.data = value
>>> t = Test()
>>> t
<__main__.Test at 0x7fa91c307190>
>>> print t
<__main__.Test object at 0x7fa91c307190>
看到了么?上面打印类对象并不是很友好,显示的是对象的内存地址
下面我们重构下该类的__ repr__以及str,看看它们俩有啥区别
# 重构__repr__
class TestRepr(Test):
def __repr__(self):
return 'TestRepr(%s)' % self.data
>>> tr = TestRepr()
>>> tr 直接终端显示,不print就是面向程序员
TestRepr(hello, world!)
>>> print tr print是面向程序员
TestRepr(hello, world!)
重构__ repr__方法后,不管直接输出对象还是通过print打印的信息都按我们repr方法中定义的格式进行显示了
# 重构__str__
calss TestStr(Test):
def __str__(self):
return '[Value: %s]' % self.data
>>> ts = TestStr()
>>> ts
<__main__.TestStr at 0x7fa91c314e50>
>>> print ts
[Value: hello, world!]
你会发现,直接输出对象ts时并没有按我们str方法中定义的格式进行输出,而用print输出的信息却改变了
repr和str这两个方法都是用于显示的,str是面向用户的,而repr面向程序员。
打印操作会首先尝试str和str内置函数(print运行的内部等价形式),它通常应该返回一个友好的显示。
__ repr__用于所有其他的环境中:用于交互模式下提示回应以及repr函数,如果没有使用str,会使用print和str。它通常应该返回一个编码字符串,可以用来重新创建对象,或者给开发者详细的显示。
当我们想所有环境下都统一显示的话,可以重构repr方法;当我们想在不同环境下支持不同的显示,例如终端用户显示使用str,而程序员在开发期间则使用底层的repr来显示,实际上str只是覆盖了repr以得到更友好的用户显示。
来源:https://www.jianshu.com/p/72a47d79af9f
标签:Python,repr,str
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python爬取豆瓣电影TOP250数据
2021-12-27 12:50:17
![](https://img.aspxhome.com/file/2023/9/95199_0s.png)
用pywin32实现windows模拟鼠标及键盘动作
2023-07-04 21:26:30
PHP+MYSQL不恶补十句话
2009-12-02 10:09:00
段正淳的css笔记(5)未知图片垂直居中的方法
2007-11-01 22:06:00
python中通过selenium简单操作及元素定位知识点总结
2021-07-18 15:34:37
![](https://img.aspxhome.com/file/2023/5/95285_0s.png)
CSS hacks与争议
2007-11-19 12:56:00
![](https://img.aspxhome.com/file/UploadPic/200711/19/20071119125952144s.gif)
ASP.NET中MD5和SHA1密码保护算法的使用
2007-08-24 09:18:00
在Python编程过程中用单元测试法调试代码的介绍
2023-12-10 02:16:46
关于网站地图
2011-01-06 12:14:00
![](https://img.aspxhome.com/file/UploadPic/20111/6/116-64s.jpg)
pandas 取出表中一列数据所有的值并转换为array类型的方法
2023-10-04 15:12:52
![](https://img.aspxhome.com/file/2023/9/86469_0s.jpg)
在Windows下安装配置CPU版的PyTorch的方法
2023-07-18 15:04:17
![](https://img.aspxhome.com/file/2023/1/61991_0s.png)
asp.net C#实现解压缩文件的方法
2023-07-14 10:34:01
Python实现自动签到脚本功能
2022-07-24 21:53:40
![](https://img.aspxhome.com/file/2023/5/81865_0s.png)
如何将一个CSV格式的文件分割成两个CSV文件
2022-02-17 01:24:29
彻底删除thinkphp3.1案例blog标签的方法
2023-11-21 12:01:01
python简单读取大文件的方法
2021-04-24 04:10:47
Python五种下划线详解
2021-10-02 02:45:38
![](https://img.aspxhome.com/file/2023/6/91846_0s.png)
Python游戏开发实例之graphics实现AI五子棋
2022-12-15 10:22:27
![](https://img.aspxhome.com/file/2023/8/104928_0s.gif)
Python logging设置和logger解析
2021-07-15 22:12:52
![](https://img.aspxhome.com/file/2023/5/107955_0s.png)
微信小程序页面缩放式侧滑效果的实现代码
2023-09-02 05:21:45
![](https://img.aspxhome.com/file/2023/4/56264_0s.gif)