Skip to main content
 首页 » 编程设计

python之在 python 3.x 中声明其主体之前调用函数

2025年05月04日15zhujiabin

我知道在 python 中,所有函数都必须在使用之前定义。所以这段代码会导致错误:

hello() 
def hello(): 
    print('Hi!') 

但是在如下代码中:

def func(): 
    hello() 
 
def hello(): 
    print('Hi!') 
 
func()  

hello() 函数在定义之前被 func() 调用,它仍然有效,我不明白为什么。

那么你能否解释一下上述行为并提前致谢。

请您参考如下方法:

Python 是一种解释型语言,因此它是逐行解释的,

您的两个示例都遵循相同的逻辑,

在第二个,

func 和 hello 已被解释,因此当您调用 func() 时,它们都是已知的并因此被执行。

def func(): 
    hello() 

--> 在这一层 func 是已知的但还没有执行(调用)

def hello(): 
    print('Hi!') 

--> 在这一层,func 和 hello 都是已知的但还没有执行(调用)

func() 

--> 最后调用func时,不管func和hello是什么顺序。它们是已知的并且在内存中有一个地址。