简体   繁体   中英

Python, assign function to variable, change optional argument's value

Is it possible to assign a function to a variable with modified default arguments?

To make it more concrete, I'll give an example. The following obviously doesn't work in the current form and is only meant to show what I need:

def power(a, pow=2):
    ret = 1
    for _ in range(pow):
        ret *= a
    return ret

cube = power(pow=3)

And the result of cube(5) should be 125 .

functools.partial to the rescue:

Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords. If more arguments are supplied to the call, they are appended to args. If additional keyword arguments are supplied, they extend and override keywords.

from functools import partial

cube = partial(power, pow=3)

Demo:

>>> from functools import partial
>>> 
>>> def power(a, pow=2):
...     ret = 1
...     for _ in range(pow):
...         ret *= a
...     return ret
... 
>>> cube = partial(power, pow=3)
>>> 
>>> cube(5)
125

The answer using partial is good, using the standard library, but I think it's worth mentioning that the following approach is equivalent:

def cube(a):
   return power(a, pow=3)

Even though this doesn't seem like assignment because there isn't a = , it is doing much the same thing (binding a name to a function object). I think this is often more legible.

In specific there's a special function for exponents:

>>> 2**3
8

But I also solved it with a lambda function, which is a nicer version of a function pointer.

# cube = power(pow=3)  # original
cube = lambda x: power(x,3)

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