The eval() takes three parameters:html
- 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代碼執行,並返回執行結果。官方文檔是這樣說的:python
The expression argument is parsed and evaluated as a Python expressionexpress
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未定義,因此報錯app
這個東西存在的意義?在stackoverflow看到了一個例子:ui
>>> 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。this
https://stackoverflow.com/questions/9383740/what-does-pythons-eval-dolua
http://www.javashuo.com/article/p-zhcuehdb-de.htmlcode
https://www.programiz.com/python-programming/methods/built-in/evalhtm