本文参考自:

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. 【转】H5 - HTML5新增标签

    下面分别是传统的div+css的页面布局方式 下面是HTML5布局方式: 是不是精简了很多呢  现在来说说图片中出现的标签: 结构标签:(块状元素) 有意义的div artical 标记定义一篇文章  ...

  2. Spring定时器调用Hibernate方法无法获得SessionFactory的解决办法

    由于在Spring定时器中无法通过注解的方式获取bean,因此需要通过原生的方式获取.获取session的方式如下: WebApplicationContext wac = ContextLoader ...

  3. Java IO流-File类的使用示例-创建文件夹和文件的正确方法

    当创建一个文件时,比如:E:\\test\\test.txt,此时若文件夹test不存在,那么直接创建文件会出错,故首先要判断文件夹是否存在,不存在的话要首先创建文件夹. public class F ...

  4. 浅谈C#中show和showDialog的区别

    [转载] A.WinForm中窗体显示  显示窗体可以有以下2种方法:  Form.ShowDialog方法 (窗体显示为模式窗体)  Form.Show方法 (窗体显示为无模式窗体) 2者具体区别如 ...

  5. windows下eclipse连接ubuntu伪分布式hadoop2.6.0

    环境: win10 jdk1.7 hadoop2.6.0 linux虚拟机 Ubuntu14.04 首先把安装在Ubuntu上的hadoop2.6.0.tar.gz复制到windows系统上,解压到任 ...

  6. JAVA多线程及补充

    进程 运行中的应用程序叫进程,每个进程运行时,都有自已的地址空间(内存空间)如IE浏览器在任务管器中可以看到操作系统都是支持多进程的 线程 线程是轻量级的进程,是进程中一个负责程序执行的控制单元线程没 ...

  7. [codeforces] 633C Spy Syndrome 2

    原题 Trie树+dp 首先,我们可以简单的想到一种dp方式,就是如果这一段可以匹配并且可以与前一段接上,那么更新dp[i]为当前字符串的编号,然后倒推就可以得到答案. 但是,显然我们不能O(m)比较 ...

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

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

  9. python3初识selenium

    第一步:安装与配置 1.电脑上需要有火狐浏览器(默认安装在C:\Program Files (x86)\Mozilla Firefox目录下). 2.使用pip install selenium安装好 ...

  10. Educational Codeforces Round 54 (Rated for Div. 2) ABCD

    A. Minimizing the String time limit per test 1 second memory limit per test 256 megabytes Descriptio ...