当前位置:网站首页>Introduction and usage of Eval function

Introduction and usage of Eval function

2022-06-11 10:50:00 Trafalgar peak

# eval function

# eval(expression,globals=None,locals=None)

# expression: This parameter is a string ,python Will use globals Dictionary and locals Dictionaries as global and local namespaces , take expression As a python

# expression ( Technically speaking , Is a list of conditions ) Analyze and calculate .

# globals: This parameter controls a global namespace , That is, we can use functions in the global namespace when calculating expressions , If this parameter is provided ,

# And there is no custom __builtins__, Then the current environment __builtins__ Copy to your own globals in , Then we can do the calculation .

# About __builtins__, It is python Built in modules for , That is to say python Built in modules , There's no need for us import It can be used , For example, we usually use int、

# str、abs And so on in this module .

# locals: This parameter controls a local namespace , and globals similar , But when it and globals When there is a repeating part in ,locals The definition in will override globals

# Medium , That is to say globals and locals When there are conflicting parts in ,locals The final say , It has the right to decide , Subject to its . If locals Has not been Words provided , The default is globals.

Here are some simple use cases :

#  The string str Evaluate as a valid expression and return the evaluation 
a = "3*2"
print(eval(a))  #  Take off the outer layer "", Evaluate as an expression , Return at this time 6
a = 10
print(eval("a+1"))  #  return 11

#  Slice fetching 
a = "1234"
print(eval(a[0]))  #  Take the string No 0 Elements , Return at this time 1
print(eval(a[2]))  #  return 3

#  stay globals When specified :
a = 10
g = {'a': 4}
print(eval("a + 1", g))  #  The return value is 5, Because it provides globals Parameters , At this time eval The scope is g Specified Dictionary , That is to say, outside a=10 Shielded 

#  stay locals When specified :
a = 10
b = 20
c = 30
g = {'a': 6, 'b': 8}
t = {'b': 100, 'c': 10}
print(eval('a+b+c', g, t))
#  The return value is 116,g Mask out global variables a and b,locals And globals There was a conflict , here locals Play a decisive role ,b The value is t Medium b value 100

a = '["a", "b", "c"]'
print(eval(a))  #  return ['a', 'b', 'c']

原网站

版权声明
本文为[Trafalgar peak]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203012230116613.html