0
点赞
收藏
分享

微信扫一扫

Python中直接查看对象值和使用print()输出的区别


直接用代码来描述这个问题的现象:

>>> x = r'C:\windows\notepad.exe'
>>> x
'C:\\windows\\notepad.exe'
>>> print(x)
C:\windows\notepad.exe
>>> x = '''Tom said, "Let's go."'''
>>> x
'Tom said, "Let\'s go."'
>>> print(x)
Tom said, "Let's go."

仔细看的话会注意到,直接查看字符串x的值,和使用print(x)来输出字符串的值,得到的结果略有不同。原因在哪里呢?这要从Python类的特殊方法说起,在Python类中有两个特殊方法__str__()和__repr__(),前者在使用print()查看对象值时会自动调用,而后者则在直接查看对象值时自动调用。下面的代码说明了这两个特殊方法的用法,这样也就能明白上面代码运行结果了。

>>> class T:
    def __str__(self):
        return '3'
    def __repr__(self):
        return '5'
    
>>> t = T()
>>> t
5
>>> print(t)
3

补充:在Python内置类型中,特殊方法__repr__()和__str__()的解释如下:

__repr__(self, /)
     Return repr(self).
__str__(self, /)
    Return str(self).

而对于内置函数repr()的解释如下:

>>> help(repr)
Help on built-in function repr in module builtins:
repr(obj, /)
    Return the canonical string representation of the object.
    
    For many object types, including most builtins, eval(repr(obj)) == obj.

举报

相关推荐

0 条评论