了解Python中的repr()函数 [英] Understanding repr( ) function in Python

查看:159
本文介绍了了解Python中的repr()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

repr():对象的可评估字符串表示形式(可以为"eval()" 它,这意味着它是一个字符串表示形式,其结果为一个Python 对象)

repr(): evaluatable string representation of an object (can "eval()" it, meaning it is a string representation that evaluates to a Python object)

换句话说:

>>> x = 'foo'
>>> repr(x)
"'foo'"

问题:

  1. 为什么在我执行repr(x)时会得到双引号? (我不明白 当我做str(x))
  2. 为什么我做eval("'foo'")而不是x时得到'foo' 对象?
  1. Why do I get the double quotes when I do repr(x)? (I don't get them when I do str(x))
  2. Why do I get 'foo' when I do eval("'foo'") and not x which is the object?

推荐答案

>>> x = 'foo'
>>> x
'foo'

因此,名称x附加在'foo'字符串上.例如,当您呼叫repr(x)时,解释器将放置'foo'而不是x,然后呼叫repr('foo').

So the name x is attached to 'foo' string. When you call for example repr(x) the interpreter puts 'foo' instead of x and then calls repr('foo').

>>> repr(x)
"'foo'"
>>> x.__repr__()
"'foo'"

repr实际上调用了x的魔术方法__repr__,该方法给出了字符串,该字符串包含分配给x的值'foo'的表示形式.因此它将在字符串""中返回'foo',从而导致"'foo'". repr的想法是给出一个包含一系列符号的字符串,我们可以在解释器中键入这些符号,并获得与作为repr参数发送的值相同的值.

repr actually calls a magic method __repr__ of x, which gives the string containing the representation of the value 'foo' assigned to x. So it returns 'foo' inside the string "" resulting in "'foo'". The idea of repr is to give a string which contains a series of symbols which we can type in the interpreter and get the same value which was sent as an argument to repr.

>>> eval("'foo'")
'foo'

当我们调用eval("'foo'")时,与在解释器中键入'foo'相同.就像我们在解释器中直接键入外部字符串""的内容一样.

When we call eval("'foo'"), it's the same as we type 'foo' in the interpreter. It's as we directly type the contents of the outer string "" in the interpreter.

>>> eval('foo')

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    eval('foo')
  File "<string>", line 1, in <module>
NameError: name 'foo' is not defined

如果我们调用eval('foo'),则与在解释器中键入foo相同.但是没有foo变量可用,并且引发了异常.

If we call eval('foo'), it's the same as we type foo in the interpreter. But there is no foo variable available and an exception is raised.

>>> str(x)
'foo'
>>> x.__str__()
'foo'
>>> 

str只是对象的字符串表示形式(请记住,x变量引用'foo'),因此此函数返回字符串.

str is just the string representation of the object (remember, x variable refers to 'foo'), so this function returns string.

>>> str(5)
'5'

整数5的字符串表示形式是'5'.

String representation of integer 5 is '5'.

>>> str('foo')
'foo'

并且字符串'foo'的字符串表示形式是相同的字符串'foo'.

And string representation of string 'foo' is the same string 'foo'.

这篇关于了解Python中的repr()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆