python的class的__str__和__repr__(转)
2024-08-24 08:40:52
本文参考自:
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 |
最新文章
- 分享一下Java写的坦克大战游戏,相信很多人小时候玩过
- 19.dnw打不开
- Windows环境下使用Clover四叶草引导双硬盘安装OSX 10.11.5原版镜像
- 批处理学习:for语句详解【经典】
- Atitit.web三大编程模型 Web Page Web Forms 和 MVC
- C# SQLiteDataReader获得数据库指定字段的值
- 10个免费开源的JS音乐播放器插件
- WPF 3D 小小小小引擎 - &#183;WPF 3D变换应用
- The Hungarian Abhorrence Principle
- 快速了解Hibernate的使用
- 修改Vim内注释字体颜色
- 使用korofileheader插件vs code添加文件头注释和函数注释
- Typescript 学习笔记六:接口
- keydown,keypress,keyup三者之间的区别
- php函数method_exists() 与is_callable()区别
- Mysql ACID与隔离级别
- 常见的加密和解密算法—MD5
- flutter 保存图片到本地
- 最长公共子序列(LCS)思维导图
- 简单复习一下ArrayList的扩容原理
热门文章
- c# log
- direct.h头文件(对目录操作)
- linux tcpdump抓包,wireshark实时解析
- HDU 2131 Probability
- 数据结构—队列(Queue)
- P3032 [USACO11NOV]二进制数独Binary Sudoku
- 【题解】POI2014FAR-FarmCraft
- [Leetcode] Convert sorted list to binary search tree 将排好的链表转成二叉搜索树
- SQLMap的前世今生(Part1)
- 2017福建省赛 FZU2272~2283