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 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() 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.

What is the difference between __str__ and __repr__ in Python的更多相关文章

  1. python中__str__与__repr__的区别

    __str__和repr __str__和__repr__都是python的内置方法,都用与将对象的属性转化成人类容易识别的信息,他们有什么区别呢 来看一段代码 from math import hy ...

  2. python 的特殊方法 __str__和__repr__

    __str__和__repr__ 如果要把一个类的实例变成 str,就需要实现特殊方法__str__(): class Person(object): def __init__(self, name, ...

  3. __str__与__repr__

    在讲解之前,我们先来了解下str和repr的区别:两者都是用来将数字,列表等类型的数据转化为字符串的形式.不同之处在于str更加类似于C语言中使用printf输出的内容,而repr输出的内容会直接将变 ...

  4. python之反射和内置函数__str__、__repr__

    一.反射 反射类中的变量 反射对象中的变量 反射模块中的变量 反射本文件中的变量 .定义:使用字符串数据类型的变量名 来获取这个变量的值 例如: name = 'xiaoming' print(nam ...

  5. python __str__() 和 __repr__()是干啥的

    1. 没定义__str__() print的时候得不到自己想要的东西 类默认转化的字符串基本没有我们想要的一些东西,仅仅包含了类的名称以及实例的 ID (理解为 Python 对象的内存地址即可).虽 ...

  6. isinstance,issubclass,内置函数__str__和__repr__,__format__,dir()函数

    isinstance(obj,cls) 检查是否obj是否是类 cls 的对象 #对象与类之间的关系 判断第一个参数是否是第二个参数的实例 # 身份运算 # 2 == 3 # 值是否相等# 2 is ...

  7. 9.4、__del__、__doc__、__dict__、__module__、__getitem__、__setitem__、__delitem__、__str__、__repr__、__call__

    相关内容: __del__.__doc__.__dict__.__module__.__getitem__.__setitem__.__delitem__.__str__.__repr__.__cal ...

  8. python 全栈开发,Day24(复习,__str__和__repr__,__format__,__call__,__eq__,__del__,__new__,item系列)

    反射: 使用字符串数据类型的变量名来使用变量 wwwh即what,where,why,how  这4点是一种学习方法 反射 :使用字符串数据类型的变量名来使用变量 1.文件中存储的都是字符串 2.网络 ...

  9. python全栈开发day23-面向对象高级:反射(getattr、hasattr、setattr、delattr)、__call__、__len__、__str__、__repr__、__hash__、__eq__、isinstance、issubclass

    一.今日内容总结 1.反射 使用字符串数据类型的变量名来操作一个变量的值. #使用反射获取某个命名空间中的值, #需要 #有一个变量指向这个命名空间 #字符串数据类型的名字 #再使用getattr获取 ...

随机推荐

  1. C#标识符与关键字

    标识符是指在程序中用来表示实物的单词,是分配给类型(类.结构.枚举.接口或委托).成员.变量或命名空间的名称.有效标识符必须遵循以下原则: 标识符不能以数字开头也不能包含空格: 标识符可以包含大小写字 ...

  2. Docker-Linux环境安装

    不同服务器操作系统安装命令不同,例如centOS默认用yum,Ubuntu可能默认用apt-get.这里推荐一种安装方式,通过下载shell脚本 https://get.docker.com,会检测操 ...

  3. C语言面试基础知识整理

    一.预处理 1.什么是预编译?何时需要预编译? (1)预编译又称预处理,是做些代码文本的替换工作,即程序执行前的一些预处理工作.主要处理#开头的指令,如拷贝#include包含的文件代码.替换#def ...

  4. 【原】Java学习笔记032 - 多线程

    package cn.temptation; public class Sample01 { public static void main(String[] args) { /* * [进程]:正在 ...

  5. SpringBoot Mybatis 使用LocalDateTime

    mybatis-spring-boot-starter 2.0.1 会报错,不知道如何解决(建议先不用) mybatis-spring-boot-starter 2.0.1 - 1.3.2 版本不会报 ...

  6. Windows下查看硬连接引用技术

    Win10有了bash,可以方便的进入并用ll查看文件的硬连接数. 但是用powershell直接查看就比较麻烦了,比较曲折的找到了方法: fsutil hardlink list [filename ...

  7. 既然CPU一次只能执行一个线程,那多线程存在的意义是什么?

    今天看到了一篇文章,终于解除了一直的疑惑.         原文链接:https://www.cnblogs.com/qingbafengliuxia/p/10171638.html CPU的时间是按 ...

  8. extjs 中比较常见且好用的监听事件

    ComboBox listeners:{ expand:function(){ //此函数是,点击下拉框展开的时候事件 }, select:function(com, record, index){ ...

  9. Python开发【框架篇】Django的Form组件

    Django的Form主要具有一下几大功能: 生成HTML标签 验证用户数据(显示错误信息) HTML Form提交保留上次提交数据 初始化页面显示内容 小试牛刀 1.创建Form类 from dja ...

  10. 你所不知道的ASP.NET Core MVC/WebApi基础系列(一)

    前言 最近发表的EF Core貌似有点多,可别误以为我只专攻EF Core哦,私下有时间也是一直在看ASP.NET Core的内容,所以后续会穿插讲EF Core和ASP.NET Core,别认为你会 ...