Phương thức eval() của Python dùng để phân tích chuỗi biểu thức (expression string) như biểu thức Python và chạy biểu thức đó trong chương trình.
Cú pháp
Cú pháp chung của phương thức eval() trong Python:
eval(expression, globals=None, locals=None)
Trong đó:
expression: tham số chuỗi bắt buộc, đây là chuỗi biểu thức được phân tích và thực thi như biểu thức Python.
globals: tham số tùy chọn là dictionary dùng để chỉ định các biểu thức có sẵn để thực thi. Nếu không nêu rõ, các phương thức built-in chuẩn có sẵn như '__builtins__': None.
locals: tham số tùy chọn, dùng để chỉ định biến cục bộ và phương thức có sẵn cho hàm eval().
Để hiểu rõ hơn eval(), hãy xem qua các ví dụ khác nhau.
eval() đơn giản
str1 = 'Hello' print(eval('str1 =="Hello"')) print(eval('str1 + ", Python"')) Kết quả
True Hello, Python
eval() với input từ người dùng
from math import * for l in range(1,3): func = input("Enter Math Function to Evaluate:\n") try: print(eval(func)) except Exception as ex: print(ex) break print('Done') Kết quả
Enter Math Function to Evaluate: abs(-42) 42 Enter Math Function to Evaluate: max(12, 3, 4 , 2, 17) 17 Done
eval() với globals và locals
Trước khi hiểu các hàm cần truyền cho eval(), hãy lấy danh sách tất cả hàm và biến có trong phạm vi global và local.
from math import * def square_root(n): return sqrt(n) # In bảng symbol global hiện tại dưới dạng dictionary print('List of Global symbols:\n',globals()) # In bảng symbol local hiện tại dưới dạng dictionary print('\nList of Local symbols:\n',locals()) # In danh sách tên trong phạm vi local hiện tại print('\nList of names in current local scope:\n',dir()) Kết quả
List of Global symbols: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:/Python/Python361/eval_example1.py', 'acos': <built-in function acos>, 'acosh': <built-in function acosh>, 'asin': <built-in function asin>, 'asinh': <built-in function asinh>, 'atan': <built-in function atan>, 'atan2': <built-in function atan2>, 'atanh': <built-in function atanh>, 'ceil': <built-in function ceil>, 'copysign': <built-in function copysign>, 'cos': <built-in function cos>, 'cosh': <built-in function cosh>, 'degrees': <built-in function degrees>, 'erf': <built-in function erf>, 'erfc': <built-in function erfc>, 'exp': <built-in function exp>, 'expm1': <built-in function expm1>, 'fabs': <built-in function fabs>, 'factorial': <built-in function factorial>, 'floor': <built-in function floor>, 'fmod': <built-in function fmod>, 'frexp': <built-in function frexp>, 'fsum': <built-in function fsum>, 'gamma': <built-in function gamma>, 'gcd': <built-in function gcd>, 'hypot': <built-in function hypot>, 'isclose': <built-in function isclose>, 'isfinite': <built-in function isfinite>, 'isinf': <built-in function isinf>, 'isnan': <built-in function isnan>, 'ldexp': <built-in function ldexp>, 'lgamma': <built-in function lgamma>, 'log': <built-in function log>, 'log1p': <built-in function log1p>, 'log10': <built-in function log10>, 'log2': <built-in function log2>, 'modf': <built-in function modf>, 'pow': <built-in function pow>, 'radians': <built-in function radians>, 'sin': <built-in function sin>, 'sinh': <built-in function sinh>, 'sqrt': <built-in function sqrt>, 'tan': <built-in function tan>, 'tanh': <built-in function tanh>, 'trunc': <built-in function trunc>, 'pi': 3.141592653589793, 'e': 2.718281828459045, 'tau': 6.283185307179586, 'inf': inf, 'nan': nan, 'square_root': <function square_root at 0x055246F0> } List of Local symbols: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:/Python/Python361/eval_example1.py', 'acos': <built-in function acos>, 'acosh': <built-in function acosh>, 'asin': <built-in function asin>, 'asinh': <built-in function asinh>, 'atan': <built-in function atan>, 'atan2': <built-in function atan2>, 'atanh': <built-in function atanh>, 'ceil': <built-in function ceil>, 'copysign': <built-in function copysign>, 'cos': <built-in function cos>, 'cosh': <built-in function cosh>, 'degrees': <built-in function degrees>, 'erf': <built-in function erf>, 'erfc': <built-in function erfc>, 'exp': <built-in function exp>, 'expm1': <built-in function expm1>, 'fabs': <built-in function fabs>, 'factorial': <built-in function factorial>, 'floor': <built-in function floor>, 'fmod': <built-in function fmod>, 'frexp': <built-in function frexp>, 'fsum': <built-in function fsum>, 'gamma': <built-in function gamma>, 'gcd': <built-in function gcd>, 'hypot': <built-in function hypot>, 'isclose': <built-in function isclose>, 'isfinite': <built-in function isfinite>, 'isinf': <built-in function isinf>, 'isnan': <built-in function isnan>, 'ldexp': <built-in function ldexp>, 'lgamma': <built-in function lgamma>, 'log': <built-in function log>, 'log1p': <built-in function log1p>, 'log10': <built-in function log10>, 'log2': <built-in function log2>, 'modf': <built-in function modf>, 'pow': <built-in function pow>, 'radians': <built-in function radians>, 'sin': <built-in function sin>, 'sinh': <built-in function sinh>, 'sqrt': <built-in function sqrt>, 'tan': <built-in function tan>, 'tanh': <built-in function tanh>, 'trunc': <built-in function trunc>, 'pi': 3.141592653589793, 'e': 2.718281828459045, 'tau': 6.283185307179586, 'inf': inf, 'nan': nan, 'square_root': <function square_root at 0x055246F0> } List of names in current local scope: ['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'square_root', 'tan', 'tanh', 'tau', 'trunc' ] Dưới đây ta thấy, có thể chỉ định giá trị globals là dictionary rỗng trong eval:
>>> print(eval('dir()', {})) ['__builtins__'] Xem ví dụ khác: cho phép truy cập chỉ một vài phương thức từ module math.
from math import * for l in range(1, 4): func = input("Enter Math Function to Evaluate.\nAllowed Functions are: abs(x) and pow(x,y):\n") try: print(eval(func, {'absolute': abs, 'pow': pow})) except Exception as ex: print(ex) break print('Done') Kết quả
Enter Math Function to Evaluate. Allowed Functions are: abs(x) and pow(x,y): abs(-74) 74 Enter Math Function to Evaluate. Allowed Functions are: abs(x) and pow(x,y): pow(2,7) 128.0 Enter Math Function to Evaluate. Allowed Functions are: abs(x) and pow(x,y): sqrt(47) name 'sqrt' is not defined Done