Tuesday 15 July 2014

python variable scope in nested functions -


I'm reading this about the decorator.

Step 8 , there is a function defined:

  def external (): x = 1 def internal (): print x # 1 return internal   

and if we move by:

  & gt; & Gt; & Gt; Foo = External ()> & gt; & Gt; & Gt; Foo.func_closure # doctest: + ELLIPSIS   

This X does not print according to the explanation:

Everything works according to Python's scoping rules- X Our function is a local variable in the outer. When moving the inner Python to the inner point x #, the local variable is detected and it appears in the scope of not getting it, which looks for it in an external form.

But the point of view about the life of the variable about things about it? Our variable x function is local to external, which means that it only exists when the function is running externally. We are not able to call without an external call, so according to our experiments according to our Python, we should have any kind of internal and perhaps a runtime error.

However, I do not really understand what the meaning of the second paragraph is.

I understand that internal () gets the value of x but why is it not printed x?

UPDATE :

Thanks for the answer, now I understand the reason " Return Inner "There is only one pointer for internal () but it is not executed, this is the reason why internal () does not print X because it to

You are not calling internal . You have said external , which gives internal , but without calling it. If you want to call internal , then foo () (since you external name foo ).

The paragraph quoted by you is tangent to this issue. You say that you already understand why internal gets the value of x , which is interpreting paragraphs, in fact, if a local variable is nested Function, and nested function is returned, the value of variable is stored with returned function, even if that variable was not activated until it was active. Typically x will end after external , because x is only localized on external but External returns internal , which is still required to access x if it is required to close x , therefore It can still be accessed later by internal .

No comments:

Post a Comment