On 17.10.2016 10:52, chenyong20...@gmail.com wrote:
Hi,

i'm confused by a piece of code with parenthese as this:

----------------code 1------------------------------
def outer():
...   def inner():
...     print 'inside inner'
...   return inner
...
foo = outer()
foo
<function inner at 0x9546668>
foo()
inside inner



----------------code 2-------------------------------
def outer():
...   def inner():
...     print 'inside inner'
...   return inner()
...
foo = outer()
inside inner
foo
foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable


the difference between these two piece of code is that the code 2 has a "()" when 
"return inner".

My questions are:
(1) what is the function difference between these two pieces of code? what does "return 
inner()" and "return inner" mean?
(2) when foo = outer() is run, why output is defferent for two pieces of code?

thanks


I suggest you look at a simpler example first:

def func():
    print('inside func')

func()
a = func
b = func()

print(a)
print(b)

and see what that gives you.
There are two things you need to know here:

- functions are callable objects and the syntax to call them (i.e., to have them executed) is to append parentheses to their name; without parentheses you are only referring to the object, but you are *not* calling it

- functions without an explicit return still return something and that something is the NoneType object None. So the function above has the side-effect of printing inside func, but it also returns None and these are two totally different things

Once you have understood this you can try to go back and study your original more complicated example.

Best,
Wolfgang

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to