0

today I learn some python.

When I try to write some code, I had some questions.

def outer(a, b):
    def inner():
        return a+b
    return inner
a=outer(4, 3)
print(a)
print(a())

<function outer.<locals>.inner at 0x0000028F37C519D0

7

and this code

def outer2(a, b):
    def inner2(c, d):
        return c + d
    return inner2(a, b)
b = outer2(4,3)
print(b)
print(b())

7

TypeError Traceback (most recent call last) <ipython-input-41-b2c9e3844269> in <module> 5 b = outer2(4,3) 6 print(b) ----> 7 print(b()) TypeError: 'int' object is not callable

I really want to know difference between a and b , anyone can help me? Thank you very much

  • Welcome to SO! Well, on one hand you're returning a function object. On the other hand, you're calling the function and returning a result. `7()` is illegal, an `int` object is not callable as the error says. Closure seems irrelevant here. – ggorlen Mar 30 '21 at 03:40

1 Answers1

0

The problem lies in this line : return inner2(a, b)

what you did was: You are actually invoking a function inner2(c,d) and passing an argument to it.Which will eventually return an integer.

what you should do instead: Do not invoke a function with arguments, just return the reference : return inner2.

You code should look something like this now:

def outer2(a, b):
    def inner2():
        return a + b
    return inner2

#b now holds the reference to a function inner2()                                                                                                                      
b = outer2(4,3)

#prints the reference to the function object                                                                                                                            
print(b)

#invokes the function inner2 and use the arguments a,b from an outer function.                                                                                                               
print(b())

This is called currying in python i.e, a function returning another function: Here to get some ideas

ishwor kafley
  • 938
  • 14
  • 32
  • Umm...thank for your answer, but that isn't my question I want to know ``` print(a) print(a()) vs print(b) print(b()) ``` – SQL-FISH Mar 30 '21 at 05:21