简体   繁体   中英

Passing SOME of the parameters to a function in python

Let's say I have:

def foo(my_num, my_string):
    ...

And I want to dynamically create a function (something like a lambba) that already has my_string, and I only have to pass it my_num:

foo2 = ??(foo)('my_string_example')
foo2(5)
foo2(7)

Is there a way to do that?

This is what functools.partial would help with:

from functools import partial

foo2 = partial(foo, my_string="my_string_example")

Demo:

>>> from functools import partial
>>> def foo(my_num, my_string):
...     print(my_num, my_string)
... 
>>> foo2 = partial(foo, my_string="my_string_example")
>>> foo2(10)
(10, 'my_string_example')
>>> foo2(30)
(30, 'my_string_example')

This should do it:

>>> def foo(a, b):
...    return a+b
...
>>> def makefoo2(a):
...    def f(b):
...        return foo(a,b)
...    return f
...
>>> foo2 = makefoo2(3)
>>> foo2(1)
4

Obviously you can vary the definition of foo to taste.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM