简体   繁体   English

在python 3.x中声明函数之前先调用函数

[英]Calling a function before declaring its body in python 3.x

I know that in python, all functions must be defined before any are used. 我知道在python中,必须先定义所有函数,然后才能使用任何函数。 So this code will result in an error: 因此,此代码将导致错误:

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

But in a code like the one bellow: 但是在像下面这样的代码中:

def func():
    hello()

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

func() 

The hello() function is called by func() before it's defined and it still works and I don't understand why. hello()函数在定义之前由func()调用,它仍然有效,我不明白为什么。

So can you please explain the above behavior and thanks in advance. 因此,请您能解释一下上述行为,并在此先感谢。

Python is an interpreted language, therefore it is interpreted line by line, Python是一种解释性语言,因此它是逐行解释的,

Both your examples follow the same logic, 您的两个示例都遵循相同的逻辑,

in the second one, 在第二个中

func and hello have already been interpreted, so when you call func() they both are known and for that executed. funchello已经被解释过,因此,当您调用func()它们都是已知的并已执行。

def func():
    hello()

--> At this level func is known but not executed (called) yet ->在此级别上,func是已知的,但尚未执行(调用)

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

--> At this level, both func and hello are known but not executed (called) yet ->在此级别上,func和hello都是已知的,但尚未执行(称为)

func()

--> Finally when you call func , no matter what order func and hello are. ->最后,当您调用func ,无论funchello是什么顺序。 They are known and have an address in memory. 它们是已知的,并且在内存中有一个地址。

Defining a new function does not execute it. 定义新功能不会执行它。 Hence the hello() function is only called when you call func() , which is done after defining hello() . 因此,仅在调用func()时才调用hello()函数,这是在定义hello()之后完成的。

I think this is because Python code is parsed top-down, and whenever the interpreter sees a function call, it has to execute it right away , so if it's not defined (yet), this will be an error. 我认为这是因为Python代码是自上而下解析的,并且每当解释器看到函数调用时, 它都必须立即执行它 ,因此,如果尚未定义它,这将是一个错误。

On the other hand, if this function isn't being called now, but the call appears in a definition of another function, the interpreter 'says': "Okay, there should be a function called hello , so I'm gonna look for it". 另一方面,如果现在不调用此函数,但是该调用出现在另一个函数的定义中,则解释器会说:“好吧, 应该有一个名为hello的函数,所以我要寻找它”。 If it does find it, it's OK, otherwise it's an error. 如果找到了,就可以了,否则就是一个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM