python的class的__str__和__repr__(转)
本文参考自:
https://stackoverflow.com/questions/18393701/the-difference-between-str-and-repr?noredirect=1&lq=1
在stackoverflow上,有个兄弟问了这个问题:
首先定义一个类:

class Item():
def __init__(self,name):
self._name=name def __str__(self):
return "Item's name is :"+self._name
print((Item("Car"),))

返回的是:
C:\Python35\python.exe C:/fitme/work/nltk/1.py
(<__main__.Item object at 0x000001DC3F9BB390>,) Process finished with exit code 0
更改成这样的代码后:

class Item():
def __init__(self,name):
self._name=name
# def __str__(self):
# return "Item's name is :"+self._name def __repr__(self):
return "Item's name is :" + self._name print((Item("Car"),))

返回结果是:
C:\Python35\python.exe C:/fitme/work/nltk/1.py
(Item's name is :Car,) Process finished with exit code 0
有人解答如下:
1.对于一个object来说,__str__和__repr__都是返回对object的描述,只是,前一个的描述简短而友好,后一个的描述,更细节复杂一些。
2.对于有些数据类型,__repr__返回的是一个string,比如:str('hello') 返回的是'hello',而repr('hello')返回的是“‘hello’”
3.现在是重点了:

Some data types, like file objects, can't be converted to strings this way. The __repr__ methods of such objects usually return a string in angle brackets that includes the object's data type and memory address. User-defined classes also do this if you don't specifically define the __repr__ method. When you compute a value in the REPL, Python calls __repr__ to convert it into a string. When you use print, however, Python calls __str__. When you call print((Item("Car"),)), you're calling the __str__ method of the tuple class, which is the same as its __repr__ method. That method works by calling the __repr__ method of each item in the tuple, joining them together with commas (plus a trailing one for a one-item tuple), and surrounding the whole thing with parentheses. I'm not sure why the __str__ method of tuple doesn't call __str__ on its contents, but it doesn't.

print(('hello').__str__())
print(('hello').__repr__())
有一个更简单的例子如下:
from datetime import datetime as dt
print(dt.today().__str__())
print(dt.today().__repr__())
1
2
3
4
5
|
C:\Python35\python.exe C:/fitme/work/nltk/1.py 2017-06-16 11:09:40.211841 datetime.datetime(2017, 6, 16, 11, 9, 40, 211841) Process finished with exit code 0 |
python的class的__str__和__repr__(转)的更多相关文章
- python 的特殊方法 __str__和__repr__
__str__和__repr__ 如果要把一个类的实例变成 str,就需要实现特殊方法__str__(): class Person(object): def __init__(self, name, ...
- python的__call__、__str__、__repr__、__init__、__class__、__name___、__all__、__doc__、__del__等魔术方法的作用
python中,一切都是对象 在Python中,所有以“__”双下划线包起来的方法,都统称为“Magic Method”--魔术方法 1.__call__:作用是把类实例变成一个可调用对象 在Pyth ...
- python中魔法方法__str__与__repr__的区别
提出问题 当我们自定义一个类时,打印这个类对象或者在交互模式下直接输入这个类对象按回车,默认显示出来的信息好像用处不大.如下所示 In [1]: class People: ...: def __in ...
- python类中方法__str__()和__repr__()简单粗暴总结
在交互式模式下,类中同时实现__str__()和__repr__()方法: 直接输入实例名称显示repr返回的类容: 用print打印实例名称显示str返回的内容: >>> clas ...
- python的class的__str__()和__repr__()函数
repr(object) 返回一个可以用来表示对象的可打印字符串首先,尝试生成这样一个字符串,将其传给 eval()可重新生成同样的对象 否则,生成用尖括号包住的字符串,包含类型名和额外的信息(比如地 ...
- python类中的__str__以及__repr__
一.__str__ 打印时触发 class A: def __str__(self): #打印时候执行的代码块 return 'ok' # 如果不返回字符串类型,则会报错 print(A()) #相当 ...
- python中__str__与__repr__的区别
__str__和repr __str__和__repr__都是python的内置方法,都用与将对象的属性转化成人类容易识别的信息,他们有什么区别呢 来看一段代码 from math import hy ...
- 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/ 目的 ...
- python __str__() 和 __repr__()是干啥的
1. 没定义__str__() print的时候得不到自己想要的东西 类默认转化的字符串基本没有我们想要的一些东西,仅仅包含了类的名称以及实例的 ID (理解为 Python 对象的内存地址即可).虽 ...
随机推荐
- JavaSE复习(五)网络编程
客户端:java.net.Socket 类表示.创建Socket对象,向服务端发出连接请求,服务端响应请求,两者建立连接开始通信 服务端:java.net.ServerSocket 类表示.创建Ser ...
- 用vs调试项目页面无样式
ASP.NET Development Server 上的文件授权 在文件系统网站中,静态文件(例如图像和样式表)遵守 ASP.NET 授权.例如,如果禁用了对静态文件的匿名访问,匿名用户则不能使用文 ...
- LeetCode难度和面试频率(转)
转自:http://www.cnblogs.com/ywl925/p/3507945.html ID Question Diff Freq Data Structure Algorit ...
- 设置select和option的文字居中的方法
给select设置text-align:center在火狐浏览器下ok,但是在chrome浏览器无效,然后option在两个浏览器下设置text-align:center都是无效的,解决方法,设置样式 ...
- 【算法】Prüfer编码 —— HNOI2004树的计数
的确,如果不知道这个编码的话的确是一脸懵逼.在这里放一篇认为讲的很详细的 BLOG,有关于编码的方式 & 扩展在里面都有所提及. 欢迎点此进入 --> 大佬的博客 在这里主要想推导一下最 ...
- SPOJ DQUERY (主席树求区间不同数个数)
题意:找n个数中无修改的区间不同数个数 题解:使用主席树在线做,我们不能使用权值线段树建主席树 我们需要这么想:从左向右添加一到主席树上,添加的是该数字处在的位置 但是如果该数字前面出现过,就在此版本 ...
- C&C++——段错误(Segmentation fault)
C/C++中的段错误(Segmentation fault) Segment fault 之所以能够流行于世,是与Glibc库中基本所有的函数都默认型参指针为非空有着密切关系的.来自:http://o ...
- 强大的JQuery数组封装使用
JQuery对数组的处理非常便捷并且功能强大齐全,一步到位的封装了很多原生js数组不能企及的功能.下面来看看JQuery数组的强大之处在哪. $.each(array, [callback]) 遍历 ...
- [fzu 2273]判断两个三角形的位置关系
首先判断是否相交,就是枚举3*3对边的相交关系. 如果不相交,判断包含还是相离,就是判断点在三角形内还是三角形外.两边各判断一次. //http://acm.fzu.edu.cn/problem.ph ...
- codeforces 719C. Efim and Strange Grade
C. Efim and Strange Grade time limit per test 1 second memory limit per test 256 megabytes input sta ...