Reference link: Functions in Python
I discovered a humorous artificial intelligence learning website a few days ago, which is easy to understand, and I can’t help but share it with everyone. Click to jump to the tutorial
There are many useful built-in tool functions in python. Using these small tools proficiently can definitely help you achieve twice the result with half the effort in your work. Today, because you need to use the eval() function, this function has actually been used before but because Recently, I have been busy reading papers and some other things in the direction. This thing has been slowly forgotten. I will use it today. I will learn it directly. This will be used as a record of learning.
The functional explanation given in the eval() official document is: convert the string object into a valid expression to participate in the evaluation operation and return the calculation result
Syntactically: The call is: eval (expression, globals=None, locals=None) returns the calculation result
among them:
expression is a python expression involved in calculation
globals is an optional parameter, if the attribute is not set to None, it must be a dictionary object
locals is also an optional object, if the property is not set to None, it can be any map object
Python uses a namespace to record the trajectory of variables. The namespace is a dictionary, the key is the variable name, and the value is the variable value.
When a line of code uses the value of the variable x, Python will search for the variable in all available namespaces, in the following order:
1 ) Local namespace-specifically refers to the method of the current function or class. If the function defines a local variable x, or a parameter x, Python will use it and then stop searching.
2 ) Global namespace-specifically refers to the current module. If the module defines a variable, function or class named x, Python will use it and stop searching.
3 ) Built-in namespace-global to every module. As a final attempt, Python will assume that x is a built-in function or variable.
The global namespace of python is stored in a dict object called globals(); the local namespace is stored in a dict object called locals(). We can use print (locals()) to view all variable names and variable values in the function body.
The following briefly demonstrates the use of eval() function:
#! usr/bin/env python
import math
def eval_test():
l='[1,2,3,4,[5,6,7,8,9]]'
d="{'a':123,'b':456,'c':789}"
t='([1,3,5],[5,6,7,8,9],[123,456,789])'
print'--------------------------Conversion begins-------------------- ------------'
print type(l), type(eval(l))
print type(d), type(eval(d))
print type(t), type(eval(t))
if name=="main":
eval_test()
The running result is:
Recommended Posts