博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
What is the difference between __str__ and __repr__ in Python
阅读量:5262 次
发布时间:2019-06-14

本文共 2447 字,大约阅读时间需要 8 分钟。

from

https://www.pythoncentral.io/what-is-the-difference-between-__str__-and-__repr__-in-python/

 

目的

官方解释:

object.__repr__(self): called by the repr() built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object.

object.__str__(self): called by the str() build-in function and by the print statement to compute the "informal" string representation of an object.

Quote from

两者都是对对象的表述, repr是正式的解释, str是信息形式的解释

 

基本类型的的默认实现

>>> x = 1
>>> repr(x)
'1'
>>> str(x)
'1'
>>> y = 'a string'
>>> repr(y)
"'a string'"
>>> str(y)
'a string'

      对于整数没有差别, 对于字符串, 我们可以看到差别

While the return of repr() and str() are identical for int x, you should notice the difference between the return values for str y. It is important to realize the default implementation of __repr__ for a str object can be called as an argument to eval and the return value would be a valid str object

      repr的返回值可以被eval再还原回字符串。

>>> repr(y)
"'a string'"
>>> y2 = eval(repr(y))
>>> y == y2
True

复杂对象

Therefore, a "formal" representation of an object should be callable by eval() and return the same object, if possible. If not possible, such as in the case where the object's members are referring itself that leads to infinite circular reference, then __repr__ should be unambiguous and contain as much information as possible.

     对于非基本类型的复杂对象, 则不能被eval计算还原, 这种情况必须遵守 意思清楚的 , 包括信息尽量多的原则。

>>> class ClassB(object):
...     def __init__(self, a=None):
...         self.a = a
...
...     def __repr__(self):
...         return '%s(a=a)' % (self.__class__)
...
 
>>> a = ClassA()
>>> b = ClassB(a=a)
>>> a.b = b
>>> repr(a)
"<class '__main__.ClassA'>(<class '__main__.ClassB'>(a=a))"
>>> repr(b)
"<class '__main__.ClassB'>(a=a)"

 

内置对象的可读性

The __str__ representation of now looks cleaner and easier to read than the formal representation generated from __repr__. Sometimes, being able to quickly grasp what's stored in an object is valuable to grab the "big" picture of a complex program.

      str更加注重可读性, 一眼就可以获取对象内容,不关注实现的细节。

>>> from datetime import datetime
>>> now = datetime.now()
>>> repr(now)
'datetime.datetime(2013, 2, 5, 4, 43, 11, 673075)'
>>> str(now)
'2013-02-05 04:43:11.673075'

 

Tips and Suggestions between __str__ and __repr__ in Python

  • Implement __repr__ for every class you implement. There should be no excuse.
  • Implement __str__ for classes which you think readability is more important of non-ambiguity.

 

转载于:https://www.cnblogs.com/lightsong/p/10699709.html

你可能感兴趣的文章
51nod1076 (边双连通)
查看>>
ViewPager的onPageChangeListener里面的一些方法参数:
查看>>
Jenkins关闭、重启,Jenkins服务的启动、停止方法。
查看>>
Linux pipe函数
查看>>
java equals 小记
查看>>
2019春 软件工程实践 助教总结
查看>>
Zerver是一个C#开发的Nginx+PHP+Mysql+memcached+redis绿色集成开发环境
查看>>
多线程实现资源共享的问题学习与总结
查看>>
java实现哈弗曼树
查看>>
程序的静态链接,动态链接和装载 (补充)
查看>>
关于本博客说明
查看>>
线程androidAndroid ConditionVariable的用法
查看>>
转载:ASP.NET Core 在 JSON 文件中配置依赖注入
查看>>
代码变量、函数命名神奇网站
查看>>
redis cli命令
查看>>
Problem B: 占点游戏
查看>>
python常用模块之sys, os, random
查看>>
HDU 2548 A strange lift
查看>>
Linux服务器在外地,如何用eclipse连接hdfs
查看>>
react双组件传值和传参
查看>>