eval,exec和compile有什么区别?
我一直在研究Python代码的动态评估,并遇到 eval() 和 compile() 函数以及 exec 语句。 有人可以解释一下 eval 和 exec 之间的区别,以及不同的 compile() 模式如何适应吗? #1楼 exec用于语句,不返回任何内容。 eval用于表达式,并返回表达式的值。 表达式表示“某事”,而语句表示“做某事”。 #2楼 exec 不是表达式:Python 2.x中的语句和Python 3.x中的函数。 它编译并立即评估字符串中包含的一条语句或一组语句。 例: exec('print(5)') # prints 5. # exec 'print 5' if you use Python 2.x, nor the exec neither the print is a function there exec('print(5)\\nprint(6)') # prints 5{newline}6. exec('if True: print(6)') # prints 6. exec('5') # does nothing and returns nothing. eval 是一个内置函数( 不是 语句),该函数对一个表达式求值并返回该表达式产生的值。 例: x = eval('5') # x <- 5 x = eval('%d + 6' % x) # x