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 对象的内存地址即可).虽 ...
随机推荐
- 福大软工1816:Alpha(2/10)
Alpha 冲刺 (2/10) 队名:第三视角 组长博客链接 本次作业链接 团队部分 团队燃尽图 工作情况汇报 张扬(组长) 过去两天完成了哪些任务: 文字/口头描述: 1.学习qqbot库: 2.实 ...
- [剑指Offer] 17.树的子结构
题目描述 输入两棵二叉树A,B,判断B是不是A的子结构.(ps:我们约定空树不是任意一个树的子结构) [思路]要查找树A中是否存在和树B结构一样的子树,可以分成两步: 1.第一步在树A中找到和B的根节 ...
- JVM GC Q&A(补充ing)
1.如果一个对象没有与其相连的GC ROOT,一定会被回收吗? 这个对象并非是非死不可的,这时他只是处于死缓阶段,要真正宣告一个对象的死亡,至少要经历两次标记过程:如果对象在进行可达性分析后发现并没有 ...
- 【考试记录】4.8 Path (网络流 —— 劲题)
手抄代码 + 学习指针 + 冥思苦想一晚上终于——在一瞬间开窍了.果然题目都是这样:突破了一个点,一切都是柳暗花明. 题面描述: 样例: 这道题目,首先注意到给定的边的性质:这些边在平面上构成了一棵树 ...
- 树剖模板by fcdalao
#include<bits/stdc++.h> using namespace std; ; *MX]; *MX]; int n,Index,fir[MX],fa[MX],dfn[MX], ...
- 【BZOJ 4007】[JLOI2015]战争调度 DP+搜索+状压
又是一道思路清新的小清晰. 观察题目,如果我们确定了平民或者贵族的任意一方,我们便可以贪心的求出另一方,至此20分:我们发现层数十分小,那么我们就也是状压层数,用lca转移,线性dp,至此50分(好像 ...
- Java的Properties使用及格式定义
java.util.Properties extends Hashtable<Object,Object> 方便读取 键值对 格式的文本资源工具 常用方法一览 初始化对象 new Prop ...
- MySQL使用笔记(一)安装配置
By francis_hao Nov 27,2016 一般软件的安装都是可以通过源码和安装包安装,源码安装可配置性好些,安装包安装比较省事,况且使用yum也可以解决依赖的问题,基本实现了一键 ...
- yum命令Header V3 RSA/SHA1 Signature, key ID c105b9de: NOKEY
yum命令Header V3 RSA/SHA1 Signature, key ID c105b9de: NOKEY 博客分类: linux 三种解决方案 我采取第三种方案解决的 第一种: linu ...
- MAC地址的介绍(单播、广播、组播、数据收发)
MAC地址组成 网络设备的MAC地址是全球唯一的.MAC地址长度为48比特,通常用十六进制表示.MAC地址包含两部分:前24比特是组织唯一标识符(OUI,OrganizationallyUniqueI ...