python - 这些代码有什么区别,repr 有什么作用?

标签 python

1.

>>> s = u"4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf"
>>> print s
4-12个英文字母、数字和下划线
>>> print repr(s)
u'4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf'

2.

print repr("4-12个英文字母、数字和下划线")
'4-12\xb8\xf6\xd3\xa2\xce\xc4\xd7\xd6\xc4\xb8\xa1\xa2\xca\xfd\xd7\xd6\xba\xcd\xcf\xc2\xbb\xae\xcf\xdf'

1和2不同,但是原字符串是一样的,都是'4-12个英文字母、数字和下划线'

repr 到底做了什么?

相同的值是:

>>> print '4-12个英文字母、数字和下划线'.decode('gb2312').encode('unicode-escape')
4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf

最佳答案

我会尝试一下,“repr”是对象的机器表示,而“print”显示对象的人类可读表示。程序员可以使用内置方法“repr”、“str”和“unicode”来实现不同的可打印表示一个对象。这是一个简单的例子

class PrintObject(object):
    def __repr__(self):
        return 'repr'

    def __str__(self):
        return 'str'

    def __unicode__(self):
        return 'unicode'

现在,如果您将此对象加载到 python shell 中并使用它,您可以看到如何使用这些不同的方法来表示对象的可打印表示

Python 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from printobject import PrintObject
>>> printObj = PrintObject()
>>> printObj
>>> repr(printObj)
'repr'
>>> str(printObj)
'str'
>>> unicode(printObj)
u'unicode'

如果您只是键入实例并返回,则使用“repr”方法

>>> printObj
repr

如果您在实例上使用 print,则使用 'str' 方法

>>> print(printObj)
str

如果您在 unicode 字符串中使用该实例,则使用“unicode”方法。

>>> print(u'%s' % printObj)
unicode

当您开始编写自己的类时,这些方法会派上用场。

关于python - 这些代码有什么区别,repr 有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2084728/

相关文章:

python - keras 中 softmax 输出的一个热输入

python - ImageMagick - 在 Python 中使用 ICC 将图像 RGB 转换为 CMYK

python - Brew 升级 python 返回 "python not installed"

python - PyQt- 哪一列获得了右键单击?

python - 在二维二进制矩阵中找到岛屿的数量

python - 将带有标题的列添加到制表符分隔的文本文件?

python matplotlib : how to automatically save figures in . 图格式?

JavaScript 网页的 Python 抓取仅对 https 页面失败

python - 在 Django Admin 中使用 DateTimeField 保存模型实例会丢失微秒分辨率

python - Crontab 只运行我脚本的一部分