首页 > 解决方案 > 如果 Python 解释器逐行执行代码,函数调用之前程序中的函数定义是如何存在的?

问题描述

我研究过 Python 解释器逐行执行代码。如果是这样的话,在 Python 中的函数调用之前函数定义是如何出现的?

如果我的理解是正确的,当 Python 解释器遇到函数调用时,它会寻找合适的函数定义并执行该定义。如果是这样,Python 解释器如何执行下面的代码?

def hello( mylist ):    
   print ("Values inside the function before change: ", mylist)     
   mylist[1]=11         
   print ("Values inside the function after change: ", mylist)       
   return     

mylist = [10,12,13]        
hello( mylist )          
print ("Values outside the function: ", mylist)

标签: pythonpython-3.xfunction

解决方案


Python 正在逐行解释代码。第一行def hello( mylist ):被解释并且hello函数调用被添加到globals列表中。

print("Before definition: " + str(globals()))

def hello( mylist ):    
   print ("Values inside the function before change: ", mylist)     
   mylist[1]=11         
   print ("Values inside the function after change: ", mylist)       
   return 


print("After definition" + str(globals()))

产生以下输出:

Before definition: {'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__': 'blah.py', '__doc__': None, '__package__': None}
After definition:  {'__builtins__': <module '__builtin__' (built-in)>, '__file__': 'blah.py', '__doc__': None, '__name__': '__main__', '__package__': None, 'hello': <function hello at 0x027CAAF0>}

请注意,在定义函数后,函数“hello”出现在打印字典的末尾hello。但是,函数中的代码还没有被执行,因为它还没有被调用。

函数中的代码只执行您调用的一个hello( mylist )

这意味着你不能调用一个函数,直到它被定义。例如,将调用放在hello函数定义之上会产生名称错误:

>>> NameError: name 'hello' is not defined

推荐阅读