python - 如果 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)
解决方案
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
推荐阅读
- tensorflow - tensorflow中变量初始化后的OOM错误
- java - Java错误的参数数量
- c# - 从批处理文件启动 WPF 应用程序时,mainWindow_Closing 事件不起作用
- swift - 将数据传递给由外部事件触发的 ViewController
- php - php。在 /tmp 下上传临时文件的权限。如何配置
- json - Node.js GET 请求有时会收到 HTML 文档而不是 JSON 并崩溃
- python - Tkinter 按钮未注册点击
- python - 用 Python 绘制简单的图形
- java - 活动视图模型在旋转时重新创建
- oracle - 密码参数 Oracle Apex