一、str() VS repr() 函数
1、str()函数把一个对象转化为字符串(供人阅读的形式),repr()函数返回一个对象的字符串表现形式(供解释器读取的形式)
>>>str(234)
'234'
>>>repr(234)
'234'
>>>str('Good Day')
'Good Day'
>>>repr('Good Day')
'' 'Good Day' '' # 单引号外面加双引号是什么鬼?
>>> l = 'a list'
>>>str(l)
'a list'
>>>repr(l)
'' 'a list' '' #单引号外面加双引号,什么鬼?
2、repr()函数的结果一般能通过eval()求值的方法获取到原对象
>>>eval(repr(l))
'a list'
3、对于类对象,对类实例调用repr()函数,返回其class、module、address
>>>class Student():
pass
>>>s = Student()
>>>repr(s)
'<__main__.Student object at 0x000000E6F81dc18>'
>>>str(s)
'<__main__.Student object at 0x000000E6F81dc18>'
>>>s
<__main__.Student object at 0x000000E6F81dc18> # 直接显示变量调用__repr__()方法,想要直接显示的结果是可直接阅读的信息,要改写__repr__()方法
>>>print(s)
<__main__.Student object at 0x000000E6F81dc18> # 想打印出可直接阅读的信息,要改写__str__()方法
二、__str__() VS __repr__()
>>>class Readers():
def __init__(self,nationality):
self.nationality = nationality
def __str__(self):
return 'You are %s.' % self.nationality
>>>s = Readers('Chinese')
>>>print(s)
You are Chinese.
>>>s
<__main__.Readers object at ..........................> #直接显示依然是class/object/address,因为没有改写__repr__()方法,改写方式和__str__()一样,用简便方法
>>>class Readers():
def __init__(self,nationality):
self.nationality = nationality
def __str__(self):
return 'You are %s.' % self.nationality
__repr__ = __str__ # 简便方法 __repr__ = __str__
>>>s =Readers('Chinese')
>>>s
You are Chinese.
>>>print(s)
You are Chinese