简体   繁体   中英

Python 3.x - Simple function that returns another function

I just recently started programming in Python and I've been trying to create a simple function that takes two parameters, a and b, and returns the result of the sum of a and |b|. I want to return f(a, b) and not just f. I know that I'm assigning f to be an int in my current code and so it returns "int not callable error" when I run. So I have to assign f to be a function of some sort. I'm fairly certain I'm missing something fundamental here, I'm just not sure exactly what. Thanks for any help!

from operator import add, sub

def a_plus_abs_b(a, b):
    """Return a+abs(b), but without calling abs.

    >>> a_plus_abs_b(2, 3)
    5
    >>> a_plus_abs_b(2, -3)
    5
    """
    if b < 0:
        f = sub(a, b)
    else:
        f = add(a, b)
    return f(a, b)
f = sub(a, b)

doesn't create a function it computes the result, so when you're calling f(a, b) you're calling an integer.

To fix it, assign the function in-line with a ternary to select which function to create depending on the sign of b

f = sub if b < 0 else add

Jean-Fançois's answer is great, but if you're not understanding the fundamentals behind this, you should look into another example that uses lambdas:

def returns_function_example():
    return lambda arg1: arg1 + 2

function_returned = returns_function_example()

print(function_returned(1))

# Output = 3

Run this in your debugger to see that "function_returned" in indeed a function. You can connect the dots after the "print" function is called.

Functions are first-class citizens in Pythonland, so that you can manipulate them as any other object.

Suppose you create your function:

def add(a, b): return a + b

If you write add , that's a function. But if you write add(2,4) , or add(a, b) assuming that a and b are defined, then you are calling the function, so you get a result. These are two completely different things: there is f , a callable , and f(a,b) which returns a value.

So if you write:

>>> f = add
>>> type(f)
<class 'function'>

That's what you want, you now have a function that does exactly what add does (and you could say it actually is add).

By contrast, if you write:

>>> f = add(a,b)
>>> type(f)
<class 'int'>
>>> f
11

That's a value.

So to make a long story short:

from operator import add, sub

def a_plus_abs_b(a, b):
    """
    Return a+abs(b), but without calling abs.

    >>> a_plus_abs_b(2, 3)
    5
    >>> a_plus_abs_b(2, -3)
    5
    """
    if b < 0:
        f = sub
    else:
        f = add

    return f(a, b)

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