Python Forum
how it works??? "__name__"
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how it works??? "__name__"
#1
Hi I am a new to Python. Can somebody explain me how this program works and particularly the flow of program. Why the output shows as "inner". Regards and Thanks in advance.
def outer():
    x = 3
    def inner(): 
       y = 4
       result = x+y
       return result  
    return inner 

a = outer()
print(a.__name__) 
Output:
output: inner
Gribouillis write May-31-2023, 07:47 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.

Attached Files

.py   inner.py (Size: 173 bytes / Downloads: 83)
Reply
#2
when you call outer() function on line 9 it returns the inner function and assign that return value to name a. So a is a function (i.e. inner) object
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
__name__ is not the interesting part. That is not much different than doing this:
def inner():
    return 4

a = inner
print(a.__name__)
Output:
inner
The interesting part of your example is "x". I modify the code a for a more interesting example:
def outer(x):
    def inner(y=4):
        return y**x
    return inner

square = outer(2)
cube = outer(3)
print(square(2), cube(2))
I assign two variables, "square" and "cube". When I call square(2) it returns 2 squared. When I call cube(2) it returns 2 cubed. How is this possible? In both cases I call the same function, inner(2). How can it act differently?

You may think that square is assigned to refer to inner(). If you print the type of square (print(type(square))) it even prints <class 'function'>, but this is only partially true. square is a closure, a combination of a function and a context. When you call square(2), you call inner(2), but you are calling inner(2) in a context where x == 2. When you call cube(2) you call inner(2) in a context where x == 3.
Reply
#4
There is a project, which visualizes Python code: https://pythontutor.com/visualize.html#mode=display
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020