标签:字符串 区别 glob 返回 parse class error: 存在 ref
The eval() takes three parameters:
- expression - this string as parsed and evaluated as a Python expression
- globals (optional) - a dictionary
- locals (optional)- a mapping object. Dictionary is the standard and commonly used mapping type in Python.
将字符串参数当作Python代码执行,并返回执行结果。官方文档是这样说的:
The expression argument is parsed and evaluated as a Python expression
In [1]: s = 'abc'
In [1]: s = 'abc'
In [2]: str(s)
Out[2]: 'abc'
In [7]: eval('x')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-7-e5b9369fbf53> in <module>()
----> 1 eval('x')
<string> in <module>()
NameError: name 'x' is not defined
In [8]: eval('s')
Out[8]: 'abc'
字符串 s 已经定义过,执行没问题;x未定义,所以报错
这个东西存在的意义?在stackoverflow看到了一个例子:
>>> input('Enter a number: ')
Enter a number: 3
>>> '3'
>>> input('Enter a number: ')
Enter a number: 1+1
'1+1'
>>> eval(input('Enter a number: '))
Enter a number: 1+1
2
>>>
>>> eval(input('Enter a number: '))
Enter a number: 3.14
3.14
这样区别就很明显了吧,上面的接收到的是str,下面经过eval处理后,变成了float。
https://stackoverflow.com/questions/9383740/what-does-pythons-eval-do
https://www.cnblogs.com/Xuuuuuu/p/10127029.html
https://www.programiz.com/python-programming/methods/built-in/eval
标签:字符串 区别 glob 返回 parse class error: 存在 ref
原文地址:https://www.cnblogs.com/wswang/p/12198284.html