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.py2017-06-16 11:09:40.211841datetime.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 对象的内存地址即可).虽 ...
随机推荐
- Caused by: redis.clients.jedis.exceptions.JedisDataException: WRONGTYPE Operation against a key holding the wrong kind of value
对错误类型key的操作,也就是说redis中没有你当前操作的这个key,而你用这个key去执行某些操作!检查key是否正确
- eniac世界第二台计算机
ENIAC,全称为Electronic Numerical Integrator And Computer,即电子数字积分计算机.ENIAC是世界上第一台通用计算机,也是继ABC(阿塔纳索夫-贝瑞计算 ...
- C#中的Stack的Peek操作,曝出异常
我们在遍历一个栈的时候,有时候需要判断栈顶元素,用到了Peek元素,然后再用Pop元素,但是这个时候会出现一个逻辑错误, 当用Pop删除全部栈的元素时,再用Peek就会报错, InvalidOpera ...
- Hadoop2.6.0伪分布式搭建
环境: 1.Ubuntu14.04 首先要在linux系统上新建一个账户,比如就叫做hadoop,用于专门运行hadoop. 2.配置jdk 我是使用的版本是jdk1.8. 解压:创建/usr/jav ...
- Javascript中闭包常用场景
一.前言 有准备去看Javascript框架,所以对于Javascript和原型继承有必要去了解,这边小记一下闭包比较好的例子~ 二.正文 先来一下“闭包”的解释~ 一个拥有许多变量和绑定了这些变量的 ...
- 【bzoj1806】[Ioi2007]Miners 矿工配餐 dp
题目描述 有n个物品,每个都是3种之一.现要将这n个物品分成两个序列,对于每个序列中的每个物品,可以得到 它及它前面相邻的两个物品(不足则取全部)中不同种类的个数 的收益.问最大的总收益. 输入 输入 ...
- 【题解】SDOI2016征途
就放个代码吧……实在是太套路了.不过据说有复杂度还要低很多的算法,不知道是怎么做呀…… #include <bits/stdc++.h> using namespace std; #def ...
- 【题解】洛谷P1975排序
分块,注意重复的值之间的处理.跟普通分块的操作一样的啦,具体可以参见‘不勤劳的图书管理员’. #include <bits/stdc++.h> using namespace std; # ...
- 2014end
人.事.物. 人一年了,从十六班到十六班,从j101到j101再到A207. 她:结婚,然后走了.就是这样,干脆得我都来不及留恋.是的,再也听不到她那很温柔语气,看不到她偶尔激动时就踮起脚尖.还记得晚 ...
- 【BZOJ 4832】 [Lydsy2017年4月月赛] 抵制克苏恩 期望概率dp
打记录的题打多了,忘了用开维记录信息了......我们用f[i][j][l][k]表示已经完成了i次攻击,随从3血剩j个,2血剩l个,1血剩k个,这样我们求出每个状态的概率,从而求出他们对答案的贡献并 ...