函数作为参数传递时是否被评估? [英] Are functions evaluated when passed as parameters?
本文介绍了函数作为参数传递时是否被评估?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
def处理程序(self):
self.run(self .connect)
def connect(self,param):
#do stuff ...
def run(self,connector):
self .runner = connector
当我调用self.run(self.connect)时,首先评估什么?
运行connect中的东西已经完成了吗?或连接self.connect尚未评估?
解决方案
传递函数作为参数不会调用它:
在[105]中:def f1(f):
.....:print'hi'
.....:返回f
.....:
在[106]中:def f2():
.....:print'hello'
.....:
在[107]中:f1(f2)
hi
Out [107]:< function __main __。f2>
当然,如果您将函数调用传递给另一个函数,你传递的是返回值:
pre $ $ $ $ $ $ $
hi
请注意它们的调用顺序: f2
首先被调用,并且它的返回值被传递给 f1
。
if I have some code like this:
def handler(self):
self.run(self.connect)
def connect(self, param):
#do stuff...
def run(self, connector):
self.runner = connector
What's evaluated first when I call self.run(self.connect)?
run with the stuff in connect already done? or connect with self.connect yet to be evaluated?
解决方案
Passing a function as a parameter does not call it:
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>
of course, if you pass a function call to another function, what you're passing is the return value:
In [108]: f1(f2())
hello
hi
Note the order in which they are called: f2
is called first, and its return value is passed to f1
.
这篇关于函数作为参数传递时是否被评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文