How to pass predefined arguments when storing a function

前端 未结 2 1202
臣服心动
臣服心动 2021-01-23 12:38

Is it possible to store a function with predefined arguments to be called by another function?

For example:

def function(num):
    print num

trigger=fun         


        
2条回答
  •  广开言路
    2021-01-23 12:56

    Someone already mentioned functools.partial which is preferred, but you can also use lambda functions without arguments:

    trigger1 = lambda: function(1)
    trigger2 = lambda: function(2)
    

    Note: As someone mentioned, be careful about defining functions like this in loops or by referencing any value in the lambda body that might change.

    You might end up in a situation like this:

    a = []
    for i in range(5):
        a.append(lambda: i)
    
    b = [func() for func in a]
    # equals [4, 4, 4, 4, 4]
    
    # to avoid this, do a.append(lambda i=i: i)
    

提交回复
热议问题