Are functions evaluated when passed as parameters?

前端 未结 2 907
梦谈多话
梦谈多话 2021-01-25 00:14

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          


        
2条回答
  •  悲哀的现实
    2021-01-25 00:48

    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]: 
    

    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.

提交回复
热议问题