本文参考自:

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__(转)的更多相关文章

  1. python 的特殊方法 __str__和__repr__

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

  2. python的__call__、__str__、__repr__、__init__、__class__、__name___、__all__、__doc__、__del__等魔术方法的作用

    python中,一切都是对象 在Python中,所有以“__”双下划线包起来的方法,都统称为“Magic Method”--魔术方法 1.__call__:作用是把类实例变成一个可调用对象 在Pyth ...

  3. python中魔法方法__str__与__repr__的区别

    提出问题 当我们自定义一个类时,打印这个类对象或者在交互模式下直接输入这个类对象按回车,默认显示出来的信息好像用处不大.如下所示 In [1]: class People: ...: def __in ...

  4. python类中方法__str__()和__repr__()简单粗暴总结

    在交互式模式下,类中同时实现__str__()和__repr__()方法: 直接输入实例名称显示repr返回的类容: 用print打印实例名称显示str返回的内容: >>> clas ...

  5. python的class的__str__()和__repr__()函数

    repr(object) 返回一个可以用来表示对象的可打印字符串首先,尝试生成这样一个字符串,将其传给 eval()可重新生成同样的对象 否则,生成用尖括号包住的字符串,包含类型名和额外的信息(比如地 ...

  6. python类中的__str__以及__repr__

    一.__str__ 打印时触发 class A: def __str__(self): #打印时候执行的代码块 return 'ok' # 如果不返回字符串类型,则会报错 print(A()) #相当 ...

  7. python中__str__与__repr__的区别

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

  8. 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/ 目的 ...

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

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

随机推荐

  1. ssh问题_2

    前一段时间配置hadoop集群环境,发现一个现象,教程中的命令形式是ssh hostname,当然这个hostname应该是在ssh发起者的hosts文件中和相应的IP对应:现在问题来了: 我用的是m ...

  2. css3 text-fill-color简介

    text-fill-color是什么意思呢?单单从字面上来看就是“文本填充颜色”,不过它实际也是设置对象中文字的填充颜色,和color的效果很相似.如果同时设置text-fill-color和colo ...

  3. hibernate对单表的增删改查

    ORM: 对象关系映射(英语:Object Relational Mapping,简称ORM,或O/RM,或O/R mapping) 实现对单表的增删改查 向区域表中增加数据: 第一步: 新建一个Da ...

  4. 关于IE缓存

    为了提高访问网页的速度,Internet Explorer浏览器会采用累积式加速的方法,将你曾经访问的网页内容(包括图片以及cookie文件等)存放在电脑里.这个存放空间,我们就称它为IE缓存.以后我 ...

  5. BZOJ4290 传送门

    昨天考试考了这道题,学校评测不开O2被卡的一愣一愣的. 这种题线性复杂度就线性复杂度,为什么要卡常数. 顺便提一句,GRH大爷O(m*n*ans)的算法有90分,我的O(m*n)算法75.(万恶的ST ...

  6. transitionEnd和animationEnd的一个临时解决方案

    transtionEnd需要添加前缀,并且存在多次触发问题,animationEnd也需要添加前缀,下面是一个临时性解决方案,解决了部分问题,完美方案探索中 (function(){ var body ...

  7. 【BZOJ 3316】JC loves Mkk 01分数规划+单调队列

    单调栈不断吞入数据维护最值,数据具有单调性但不保证位置为其排名,同时可以按照进入顺序找出临近较值单调队列队列两端均可删除数据但只有队末可以加入数据,仍然不断吞入数据但同时可以额外刨除一些不符合条件的数 ...

  8. 毕业答辩的PPT攻略

    关于内容: 1.一般概括性内容:课题标题.答辩人.课题执行时间.课题指导教师.课题的归属.致谢等.  2.课题研究内容:研究目的.方案设计(流程图).运行过程.研究结果.创新性.应用价值.有关课题延续 ...

  9. Astah画时序图

    Astah画时序图,666 1.生命线 时序图中表示为从对象图标向下延伸的一条虚线,表示对象存在的时间, 一般用来描述 系统 :如 客户端,代理层,缓存层,服务器层1.....服务器层N,数据库等. ...

  10. Java之戳中痛点 - (4)i++ 和 ++i 探究原理

    先看一个例子: package com.test; public class AutoIncrement { public static void main(String[] args) { int ...