函数内部函数 - 每次? [英] Function inside function - every time?
问题描述
让我们有这个代码:
def big_function():
def little_function():
.......
.........
Python文档说明 def
语句:
The Python documentation says about def
statement:
函数定义是一个可执行语句。它的执行绑定
函数名...
A function definition is an executable statement. Its execution binds the function name...
所以,问题是:
< $ c> 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.
这篇关于函数内部函数 - 每次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!