repr 更可能是用来配合 eval 的 (<- 点击查看),str 更可能是用来转换成字符串格式的html
str() 和 repr() 都会返回一个字符串
可是 str() 返回的结果更加适合于人阅读,repr() 返回的结果更适合解释器读取python
示例:函数
string = 'Hello World' print(str(string), len(str(string))) print(repr(string), len(repr(string)))
输出结果:命令行
Hello World 11 'Hello World' 13
说明 str() 返回的仍然是字符串自己,可是 repr() 返回的是带引号的字符串code
在一个类中 __repr__
、 __str__
均可以返回一个字符串htm
示例:
当类中同时有这两个方法blog
class Test(object): def __init__(self): pass def __repr__(self): return 'from repr' def __str__(self): return 'from str' test = Test() print(test) print(test.__repr__()) print(test.__str__())
输出结果:字符串
from str from repr from str
当类中只有 __str__ 方法时get
class Test(object): def __init__(self): pass def __str__(self): return 'from str' test = Test() print(test) print(test.__repr__()) print(test.__str__())
输出结果:string
from str <__main__.Test object at 0x105df89e8> from str
当类中只有 __repr__ 方法时
class Test(object): def __init__(self): pass def __repr__(self): return 'from repr' test = Test() print(test) print(test.__repr__()) print(test.__str__())
输出结果:
from repr from repr from repr
说明 print()
函数调用的是 __str__
,而命令行下直接输出时调用的是 __repr__
当类中没有 __str__
时,会调用 __repr__
,可是若是没有 __repr__
,并不会去调用 __str__