What is the difference between __str__ and __repr__ in Python
from
https://www.pythoncentral.io/what-is-the-difference-between-__str__-and-__repr__-in-python/
目的
官方解释:
object.__repr__(self): called by therepr()built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object.
object.__str__(self): called by thestr()build-in function and by the print statement to compute the "informal" string representation of an object.Quote from Python's Data Model
两者都是对对象的表述, 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()andstr()are identical forint x, you should notice the difference between the return values forstr y. It is important to realize the default implementation of__repr__for astrobject can be called as an argument toevaland the return value would be a validstrobject
repr的返回值可以被eval再还原回字符串。
>>> repr(y)"'a string'">>> y2 = eval(repr(y))>>> y == y2True
复杂对象
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.
What is the difference between __str__ and __repr__ in Python的更多相关文章
- python中__str__与__repr__的区别
__str__和repr __str__和__repr__都是python的内置方法,都用与将对象的属性转化成人类容易识别的信息,他们有什么区别呢 来看一段代码 from math import hy ...
- python 的特殊方法 __str__和__repr__
__str__和__repr__ 如果要把一个类的实例变成 str,就需要实现特殊方法__str__(): class Person(object): def __init__(self, name, ...
- __str__与__repr__
在讲解之前,我们先来了解下str和repr的区别:两者都是用来将数字,列表等类型的数据转化为字符串的形式.不同之处在于str更加类似于C语言中使用printf输出的内容,而repr输出的内容会直接将变 ...
- python之反射和内置函数__str__、__repr__
一.反射 反射类中的变量 反射对象中的变量 反射模块中的变量 反射本文件中的变量 .定义:使用字符串数据类型的变量名 来获取这个变量的值 例如: name = 'xiaoming' print(nam ...
- python __str__() 和 __repr__()是干啥的
1. 没定义__str__() print的时候得不到自己想要的东西 类默认转化的字符串基本没有我们想要的一些东西,仅仅包含了类的名称以及实例的 ID (理解为 Python 对象的内存地址即可).虽 ...
- isinstance,issubclass,内置函数__str__和__repr__,__format__,dir()函数
isinstance(obj,cls) 检查是否obj是否是类 cls 的对象 #对象与类之间的关系 判断第一个参数是否是第二个参数的实例 # 身份运算 # 2 == 3 # 值是否相等# 2 is ...
- 9.4、__del__、__doc__、__dict__、__module__、__getitem__、__setitem__、__delitem__、__str__、__repr__、__call__
相关内容: __del__.__doc__.__dict__.__module__.__getitem__.__setitem__.__delitem__.__str__.__repr__.__cal ...
- python 全栈开发,Day24(复习,__str__和__repr__,__format__,__call__,__eq__,__del__,__new__,item系列)
反射: 使用字符串数据类型的变量名来使用变量 wwwh即what,where,why,how 这4点是一种学习方法 反射 :使用字符串数据类型的变量名来使用变量 1.文件中存储的都是字符串 2.网络 ...
- python全栈开发day23-面向对象高级:反射(getattr、hasattr、setattr、delattr)、__call__、__len__、__str__、__repr__、__hash__、__eq__、isinstance、issubclass
一.今日内容总结 1.反射 使用字符串数据类型的变量名来操作一个变量的值. #使用反射获取某个命名空间中的值, #需要 #有一个变量指向这个命名空间 #字符串数据类型的名字 #再使用getattr获取 ...
随机推荐
- powershell-脚本运行权限政策
获取当前策略:Get-ExecutionPolicy 设置当前策略:Set-ExecutionPolicy Unrestricted Restricted——默认的设置, 不允许任何script运行 ...
- 使用Log4Net进行错误日志记录
http://blog.csdn.net/zdw_wym/article/details/48802821
- Git + Docker + Jenkins自动化部署web到Linux(Centos)
1.把代码托管到Github上 2.安装Docker 3.安装Jenkins 4.在项目中编写Dockerfile.publish.sh (1)Dockerfile内容 # 基于dotnet基础环境构 ...
- R语言学习——数据合并及绘制密度分布曲线图
setwd("E:/08_cooperation/07_X-lab/06-Crosstalk/Aadapter_primer")# 读取lane01.txt,并对其按列进行相加处理 ...
- WEB框架-Django框架学习(一)-基础层级关系
今日主要内容为Django架构,主要有路由层,视图层和模板层 1. Django的路由层 URL配置(URLconf)就像Django 所支撑网站的目录.它的本质是URL与要为该URL调用的视图函数之 ...
- CSAPP:第十二章 并发编程
CSAPP:第十二章 并发编程 12.1 线程执行模型12.2 多线程之间并发通信12.3 其他并发问题 使用应用级并发的应用程序称为并发程序.现代操作系统提供三种基本的构造并发程序的方法: 进程 ...
- [POI2015]PUS
嘟嘟嘟 这题只要往正确的方面想,就很简单. 首先,这是一道图论题! 想到这,这题就简单了.对于两个数\(i\)和\(j\),如果\(i\)比\(j\)大,就从\(i\)向\(j\)连边.然后如果图中存 ...
- 28 Python初学(事件驱动模型)
参考文章地址:http://www.cnblogs.com/yuanchenqi/articles/5722574.html 两个步骤: recvfrom 系统调用 : 拷贝数据 从kernel到数据 ...
- JQuery:怎么动态切换一个元素的显示、隐藏呢?原来隐藏就显示,原来显示就隐藏
使用toggle() 方法:<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"& ...
- 安装Cnario提示.Net 3.5安装错误, 检查Windows系统更新提示无法检查到更新, 安装.Net 3.5提示"Windows无法完成请求的更改, 错误代码:0x800F081F"
症状: Windows检查系统更新时提示无法完成, 尝试安装.Net 3.5等组件时都无法完成, 错误代码: 0x800F081F 原因: 可能时设置了禁止Windows自动更新, 需要重新打开 解决 ...