__repe__和__str__函数的区别

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dqchouyang/article/details/79951645

先看下例子:

>>> class Tesa(object):
...     def __init__(self, value='a'):
...         self.data = value
... 
>>> a = Tesa()
>>> a
<__main__.Tesa object at 0x10f91b828>
>>> 
>>> print(a)
<__main__.Tesa object at 0x10f91b828>
>>> 
>>>
>>> 
>>> class Tesb(object):
...     def __init__(self, value='b'):
...         self.data = value
...     def __repr__(self):
...         return 'fdsfdsf'
... 
>>> 
>>> b = Tesb()
>>> b
fdsfdsf
>>> print(b)
fdsfdsf
>>> repr(b)
fdsfdsf
>>> str(b)
fdsfdsf
>>> 
>>> 
>>> 
>>> class Tesc(object):
...     def __init__(self, value='a'):
...         self.data = value
...     def __str__(self):
...         return "iiiib"
... 
>>> c = Tesc()
>>> 
>>> c
<__main__.Tesc object at 0x10f91bb70>
>>> print(c)
iiiib
>>> 
>>> str(c)
'iiiib'
>>> repr(d)
'<__main__.Tesc object at 0x10f91bb70>'
>>> 
>>> 
>>> 
>>> class Test(object):
...     def __init__(self, value='a'):
...         self.data = value
...     def __repr__(self):
...         return 'fdsfdsf'
...     def __str__(self):
...         return "iiiii"
... 
>>> t = Test('ffee')
>>> t
fdsfdsf
>>> print(t)
iiiii
>>> 
>>> repr(t)
'iiiii'
>>> 

总结:
__repe__函数返回的信息是数据的元(基础)数据,一般供给程序员查看,通过object和repr(object)来调用
__str__函数返回的是经过转换(修饰)过的数据,一般给用户查看,通过print (objects)来调用

注意:当类没有__str__函数时,print(object)函数会调用__repe__函数的返回值。
这里写图片描述

猜你喜欢

转载自blog.csdn.net/dqchouyang/article/details/79951645