zoukankan      html  css  js  c++  java
  • Python中eval与exec用法的区别

    Python中eval,exec这两个函数有着相似的输入参数类型和执行功能,因此在用法上经常出现混淆,以至经常用错,程序易抛出错误。下面主要通过这两个函数的语法来阐述区别,并用例子来进一步说明。

    首先看下官方文档对这两个函数的说明:

    (1)eval(expr, globals=None, locals=None, /)

    Evaluate the given expr in the context of globals and locals.
    This call returns the expr result.
    The expr may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

    (2)exec(stmts, globals=None, locals=None, /)

    Execute the given stmts in the context of globals and locals.

    The stmts may be a string representing one or more **Python statements**
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.
    

    特别注意上述黑体字,发现eval与exec的第一个输入参数虽然都是string,但eval中的是表达式,而exec中的是声明,所以区分这两个函数的问题就转化成了什么是表达式,什么是声明的问题,这两个概念必须搞清楚,才能理清楚这两个函数的用法。

    Python中,表达式有比如比较大小,数字相乘,列表切片,函数调用等等,而声明则比较特殊,有assignment statement,expression statement(call function,instance method etc),print statement,if statement,for statement,while statement,def statement,try statement...

    注意到表达式与声明存在某些交集,如函数调用,实例方法调用,print等,因此对于这些交集,都可以传入这两个函数,而除此之外,最好将expression传入eval,而statement传入exec,否则,要么抛出异常,要么不能实现既定的目标。

    接下来用实例来阐述。

    eval('x=1')#赋值声明,传入eval报错
    
      File "<string>", line 1
        x=1
         ^
    SyntaxError: invalid syntax
    
    exec('x=1');x
    
    1
    
    eval('1<2')#比较表达式
    
    True
    
    exec('1<2');print('No output')#表达式,没有输出
    
    No output
    
    eval('print("print can be shown via eval")')
    
    print can be shown via eval
    
    exec('print("print can also be shown via exec")')
    
    print can also be shown via exec
    ##### 愿你一寸一寸地攻城略地,一点一点地焕然一新 #####
  • 相关阅读:
    存储:块存储/文件存储/对象存储
    系统调用system call以及strace/dtruss
    JBoss EAP应用服务器部署方法和JBoss 开发JMS消息服务小例子
    在IE中,JS方法名和input的name重名时,调用该方法无效
    html 使表格随着内容自动适应宽度
    Jboss 安全和优化
    java网页数据抓取实例
    Eclipse+Weblogic 12开发简单的Enterprise Application
    eclipse中整合ejb和web工程
    破解 jar 包之直接修改 .class 文件方式
  • 原文地址:https://www.cnblogs.com/johnyang/p/12333899.html
Copyright © 2011-2022 走看看