Python函数调用顺序

Viv*_*Jha 3 python interpreter call

当你运行它时,Python如何"读入"程序?例如,我不明白为什么NameError: name 'cough' is not defined下面的代码中没有:

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


def cough():
    print('cough')


if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

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

def cough():
    print('cough')


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


if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

OLI*_*KOO 11

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

在这种情况下,程序逐行读取并知道函数cough()main()定义.以后什么时候main()叫Python知道它是什么,什么时候main()调用cough()Python也知道它是什么.

def cough():
    print('cough')


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


if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

在另一个案例中(下图),它是一回事.只是Python学习main()之前的功能cough().在这里你可能会想:" 为什么python不会抛出错误,因为它不知道caugh()里面是什么main() "好问我的朋友.

但是只要你在调用它之前定义了你的函数,一切都很好.因为记住Python不会"检查"函数是否被定义,直到你调用它.所以在这种情况下甚至cough()没有定义当python正在读取函数时main()它是可以的,因为我们main()直到cough()下面定义之后才调用.

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


def cough():
    print('cough')


if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

希望这有助于您更好地理解Python.

  • "逐行编译" - "按语句执行的语句"怎么样?这是一个更正确的描述.(因为它不是基于行的,当编译为字节码时,它发生在整个文件+每个函数上) (3认同)