聆雨淋夜 发表于 2014-09-24 13:54

关于repr 函数的小问题,前辈们帮忙解答

刚开始自学python,看到《python基础教程》P11有如下表述:“交互式解释器总是把所有表达式的值打印出来而已(都使用了相同的repr函数对结果进行呈现)”
但如下两个表达式的结果为什么不同呢?

>>> 3+4
7
>>> repr(3+4)
'7'

问题2:P22有如下表述:“input会假设用户输入的是合法的python表达式(或多或少有些与repr函数相反的意思)。”
我觉得这句话不对,input会接受数字,但repr函数只会返回字符串。
还是我理解错了呢?大家说说看法。

聆雨淋夜 发表于 2014-09-24 19:30

小伙们快来帮帮我

qianguozheng 发表于 2014-09-25 09:48

返回字符串可以转换为数字啊

聆雨淋夜 发表于 2014-09-29 17:51

回复 3# qianguozheng

朋友能帮忙回答一下第一个问题么,不懂诶


   

zsjbz 发表于 2014-09-30 12:18

python解释器在交互模式下基本上是这么做的x = exp
if x is not None:
    print repr(x)所以你的疑问其实就是print repr(3+4)
print repr(repr(3+4))

liaozd 发表于 2014-10-03 10:28

>>> type(repr(1+2))
<type 'str'>
>>> type(1+2)
<type 'int'>

python先执行了运算,然后把int3交给了repr,repr有点相当于str(3)
最好先读一下repr的library:
repr(object)

    Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval()

聆雨淋夜 发表于 2014-10-08 15:49

回复 5# zsjbz
懂了,tks


   
页: [1]
查看完整版本: 关于repr 函数的小问题,前辈们帮忙解答