How to pass predefined arguments when storing a function

前端 未结 2 1200
臣服心动
臣服心动 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:55

    You're looking for functools.partial:

    >>> import functools
    >>> def foo(number):
    ...     print number
    ... 
    >>> bar = functools.partial(foo, 1)
    >>> bar()
    1
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题