作为参数传递时是否评估函数?

itc*_*per 1 python function parameter-passing

如果我有这样的代码:

def handler(self):
   self.run(self.connect)

def connect(self, param):
   #do stuff...

def run(self, connector):
   self.runner = connector
Run Code Online (Sandbox Code Playgroud)

当我调用self.run(self.connect)时首先评估的是什么?

在连接已经完成的东西运行?或者连接self.connect还有待评估?

ask*_*han 6

将函数作为参数传递不会调用它:

In [105]: def f1(f):
   .....:     print 'hi'
   .....:     return f
   .....: 

In [106]: def f2():
   .....:     print 'hello'
   .....:     

In [107]: f1(f2)
hi
Out[107]: <function __main__.f2>
Run Code Online (Sandbox Code Playgroud)

当然,如果你将函数调用传递给另一个函数,你传递的是返回值:

In [108]: f1(f2())
hello
hi
Run Code Online (Sandbox Code Playgroud)

请注意它们的调用顺序: f2首先调用,并将其返回值传递给f1.