python函数调用顺序_Python函数调用顺序

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 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)

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()

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.

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()

Hope this helps you understand Python better.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值