Python函数调用顺序 [英] Python function calling order

查看:86
本文介绍了Python函数调用顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python在运行时如何读入程序?例如,我不明白为什么不会出现 NameError:在下面的代码中未定义名称'cough'

How does Python "read in" a program when you run it? For example, I don't understand why there wouldn't be a NameError: name 'cough' is not defined in the below code:

def main():
    for i in range(3):
        cough()


def cough():
    print('cough')


if __name__ == '__main__':
    main()

基本上,我的问题也可以说成是为什么上面和下面的程序会输出相同的东西:

Basically, my question can also be stated as why do the above and below programs output the same thing:

def cough():
    print('cough')


def main():
    for i in range(3):
        cough()


if __name__ == '__main__':
    main()


推荐答案

Python是一种解释语言,它是按语句执行的语句
(感谢维普托的提示:编译为字节码时,它发生在整个文件+每个函数上)

Python is an interpreted language which is executed statement by statement (thanks to viraptor's tip: when compiling to bytecode it happens on whole file + per function)

程序下方的情况为b行y行,并且知道已定义函数 cough() main()。稍后调用 main()时,Python知道它是什么,何时 main()调用 cough() Python也知道它是什么。

In this case below the program reads line by line and knows that the function cough() and main() are defined. and later when main() is called Python knows what it is and when main() calls cough() Python knows what it is as well.

def cough():
    print('cough')


def main():
    for i in range(3):
        cough()


if __name__ == '__main__':
    main()

在另一种情况下(下),这是同一件事。只是Python会在 cough()之前了解 main()函数是什么。在这里您可能会想: 为什么python不会抛出错误,因为它不知道 main里面的 caugh()是什么( )我的朋友问得好。

In this other case (below) it is the same thing. just that Python learns what main() function is before cough(). Here you might wonder: "why won't python throw an error since it doesn't know what caugh() is inside main() ? " Good question my friend.

但是只要在调用函数之前定义了函数,就可以了。因为请记住在调用函数之前,Python不会检查函数是否已定义。。因此,在这种情况下,甚至 cough()都不会是在python读取函数 main()时定义的,这是可以的,因为我们直到<之后才调用 main() code> cough()的定义如下。

But as long as your function is defined before you call it everything is fine. Because remember Python won't "check" if a function is defined until you call it. so in this case even tho cough() is not defined when python is reading function main() it is ok because we didn't call main() until after cough() is defined below.

def main():
    for i in range(3):
        cough()


def cough():
    print('cough')


if __name__ == '__main__':
    main()

希望这可以帮助您更好地理解Python。

Hope this helps you understand Python better.

这篇关于Python函数调用顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆