简体   繁体   English

python调用函数时会发生什么?

[英]python what happens when a function is called?

I am using pdb to debug a program. 我正在使用pdb来调试程序。 I successively hit 'c' to run through the code and at each step pdb shows me which line is executed. 我先后点击'c'来运行代码,每一步pdb都显示我执行了哪一行。

Let's say we have this code: 假设我们有这个代码:

def foo(bar):
   print(bar)

foo('hey')

First, line 4 calls function foo. 首先,第4行调用函数foo。 Then pdb shows me the line 然后pdb告诉我这一行

def foo(bar)

is executed. 被执行。

Why? 为什么? Is not that line just a kind of label? 这条线不仅仅是一种标签吗? What happens before "print(bar)" is executed? 执行“print(bar)”之前会发生什么? (that comes with another 's' hit) (伴随着另一个人的打击)

EDIT: I experimented that something done is to actually check the definition. 编辑:我试验做的事情是实际检查定义。 In fact, in the case foo were a generator (that cannot be called in such a way) python still gets there and then decides to treat it as a generator (or a function depending the case..). 实际上,在foo是一个生成器(不能以这种方式调用)的情况下,python仍然会到达那里,然后决定将其视为生成器(或根据情况而定的函数)。

def is not a declaration in Python, it's an executable statement. def不是Python中的声明,它是一个可执行语句。 At runtime it retrieves the code object compiled for the function, wraps that in a dynamically created function object, and binds the result to the name following the def . 在运行时,它检索为函数编译的代码对象,将其包装在动态创建的函数对象中,并将结果绑定到def后面的名称。 For example, consider this useless code: 例如,考虑这个无用的代码:

import dis
def f():
    def g():
        return 1
dis.dis(f)

Here's part of the output (Python 2.7.5 here): 这是输出的一部分(这里是Python 2.7.5):

0 LOAD_CONST               1 (<code object g at 02852338, file ...>)
3 MAKE_FUNCTION            0
6 STORE_FAST               0 (g)

All this is usually an invisible detail, but you can play some obscure tricks with it ;-) For example, think about what this code does: 所有这些通常都是一个看不见的细节,但你可以用它来玩一些模糊的技巧;-)例如,想想这段代码的作用:

fs = []
for i in range(3):
    def f(arg=i**3):
        return arg
    fs.append(f)
print [f() for f in fs]

Here's the output: 这是输出:

[0, 1, 8]

That's because the executable def creates three distinct function objects, one for each time through the loop. 那是因为可执行的def创建了三个不同的函数对象,每次通过循环一次。 Great fun :-) 非常有趣 :-)

What happens before "print(bar)" is executed? 执行“print(bar)”之前会发生什么?

This is just an educated guess: I suppose the current IP is pushed onto the stack and then the parameters. 这只是一个有根据的猜测:我想当前的IP被推入堆栈然后是参数。 Then a new stack frame is created, the parameters are popped from stack and added as locals to the current scope. 然后创建一个新的堆栈帧,从堆栈中弹出参数并将其作为本地添加到当前作用域。 Something along this line. 沿着这条线的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM