In [38]: str('s')Out[38]: 's'
In [39]: repr('s')Out[39]: "'s'"
In [40]: eval(str('s'))Traceback (most recent call last):
File "<ipython-input-40-abd46c0c43e7>", line 1, in <module>eval(str('s'))
File "<string>", line 1, in <module>
NameError: name 's' is not defined
In [41]: eval(repr('s'))Out[41]: 's'
In [30]: str(datetime.datetime.now())Out[30]: '2017-12-07 15:41:14.002752'Disguised in string form
关于__repr__
In [32]: datetime.datetime.now()Out[32]: datetime.datetime(2017, 12, 7, 15, 43, 27, 297769)Presence in real body which allows to be manipulated directly.
class Demo:def __repr__(self):return 'repr'def __str__(self):return 'str'
demo = Demo()print(demo) # use __str__, output 'str' to stdout
s = str(demo) # __str__ is used, return 'str'r = repr(demo) # __repr__ is used, return 'repr'
import logginglogger = logging.getLogger(logging.INFO)logger.info(demo) # use __str__, output 'str' to stdout
from pprint import pprint, pformatpprint(demo) # use __repr__, output 'repr' to stdoutresult = pformat(demo) # use __repr__, result is string which value is 'str'
class C1:pass
class C2:def __str__(self):return str(f"{self.__class__.__name__} class str ")
class C3:def __repr__(self):return str(f"{self.__class__.__name__} class repr")
class C4:def __str__(self):return str(f"{self.__class__.__name__} class str ")def __repr__(self):return str(f"{self.__class__.__name__} class repr")
ci1 = C1()ci2 = C2()ci3 = C3()ci4 = C4()
print(ci1) #<__main__.C1 object at 0x0000024C44A80C18>print(str(ci1)) #<__main__.C1 object at 0x0000024C44A80C18>print(repr(ci1)) #<__main__.C1 object at 0x0000024C44A80C18>print(ci2) #C2 class strprint(str(ci2)) #C2 class strprint(repr(ci2)) #<__main__.C2 object at 0x0000024C44AE12E8>print(ci3) #C3 class reprprint(str(ci3)) #C3 class reprprint(repr(ci3)) #C3 class reprprint(ci4) #C4 class strprint(str(ci4)) #C4 class strprint(repr(ci4)) #C4 class repr
>>> eval('123')123>>> eval('foo')Traceback (most recent call last):File "<stdin>", line 1, in <module>File "<string>", line 1, in <module>NameError: name 'foo' is not defined