__str__和__repr__比较
来源:互联网 发布:淘宝被骗怎么办? 编辑:程序博客网 时间:2024/05/16 20:31
python的class的str和repr
首先定义一个类:
class Item(): def __init__(self,name): self._name=name def __str__(self): return "Item's name is :"+self._nameprint((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._nameprint((Item("Car"),))
返回结果是:
C:\Python35\python.exe C:/fitme/work/nltk/1.py(Item's name is :Car,)Process finished with exit code 0
从上边的代码中可以清晰的看出:对 repr 进行重构后,无论是直接输出对象还是打印对象的信息都是按照我们定义的格式进行输出,而对str进行重构后,仅仅是在打印时才是按照我们定义的格式输出,
有人解答如下:
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 dtprint(dt.today().__str__())print(dt.today().__repr__())
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
阅读全文
0 0
- __str__和__repr__比较
- python - __str__ 和 __repr__
- python - __str__ 和 __repr__
- python - __str__ 和 __repr__
- __str__ 和 __repr__
- python - __str__ 和 __repr__
- python __str__ 和 __repr__
- __str__()和__repr__()的调用
- 【ZZ】python - __str__ 和 __repr__
- __repr__和__str__的区别
- python中 __str__和__repr__
- Python中__str__和__repr__
- python __repr__和__str__ 的区别
- __str__和__repr__有啥区别呢?
- Python中__repr__和__str__区别
- python 的特殊方法 __str__和__repr__
- python 的特殊方法 __str__和__repr__
- python中__str__和__repr__的区别
- 适配器设置图片
- 网络获取图片和ListView
- 【项目管理和构建】——Maven下载、安装和配置(二)
- 监听器Listener
- 剑指offer之二叉树的下一个节点
- __str__和__repr__比较
- 两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同
- RecyclerView简单多条目
- 【密码学】C语言实现RSA模幂运算
- PAT 乙级 1030. 完美数列(25)
- AS报错Unable to merge dex
- 2.图层
- java鬼混笔记:lucene 5、index基本的增删查改
- POJ 2763 Housewife Wind 笔记