本文介绍了函数内部函数 - 每次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 让我们有这个代码:def big_function(): def little_function(): ....... ......... Python文档说明 def 语句:The Python documentation says about def statement:所以,问题是: def little_function()每次调用 big_function 时执行? 问题是关于 def 语句,而不是 little_function()正文。So, the question is:Does def little_function() execute every time when big_function is invoked?Question is about def statement exactly, not the little_function() body.推荐答案您可以使用 dis 模块检查字节码:You can check the bytecode with the dis module:>>> import dis>>> def my_function():... def little_function():... print "Hello, World!"......>>> dis.dis(my_function) 2 0 LOAD_CONST 1 (<code object little_function at 0xb74ef9f8, file "<stdin>", line 2>) 3 MAKE_FUNCTION 0 6 STORE_FAST 0 (little_function) 9 LOAD_CONST 0 (None) 12 RETURN_VALUE请参阅仅一次编译内部函数的代码。每次调用 my_function 时,它都会被加载并创建一个新的函数对象(在这个意义上, def little_function 每次 my_function 被调用时执行),但这不会增加很多开销。As you can see the code for the inner function is compiled only once. Every time you call my_function it is loaded and a new function object is created(in this sense the def little_function is executed every time my_function is called), but this doesn't add much overhead. 这篇关于函数内部函数 - 每次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-29 08:19