[英]Python code evaluation order?
The output of following code is 以下代码的输出是
5
3
I am new to Python, could anybody explain to me why? 我是Python的新手,有人可以向我解释原因吗?
import sys
def Main():
str='1+2'
print eval(str)
class A:
def __init__(self):
self.x = 5
a = A()
print a.x
if __name__=="__main__":
Main()
Python code is evaluated from top-down, not from Main()
. Python代码从上到下进行评估,而不是从
Main()
进行评估。
The interpreter sees the a = A()
line first, and prints ax
which is equal to 5, then it checks for the if
condition and prints eval(str)
which is 3
. 解释器首先看到
a = A()
行,并打印等于5的ax
,然后检查if
条件并打印eval(str)
为3
。
Hence the output, 因此输出,
5
3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.