您当前的位置:首页 > 计算机 > 编程开发 > Python

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

时间:12-24来源:作者:点击数:
CDSY,CDSY.XYZ

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

>>> 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.

CDSY,CDSY.XYZ
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门