Are functions evaluated when passed as parameters?

我们两清 提交于 2019-12-20 04:19:08

问题


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?


回答1:


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.




回答2:


None of the code in your question actually calls connect(), so the function is never invoked. All that self.run(self.connect) does is make self.runner a synonym for self.connect.



来源:https://stackoverflow.com/questions/15256795/are-functions-evaluated-when-passed-as-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!