The topic I found most difficult for this week's lecture is to understand how Python searched for names, specially the 'scopes and namespaces examples.' I got really stuck while I am writing this slog. After asking my father's friend who had experience programming, I learned that it is not as confusing as it appears to be, and it is pretty interesting.
Here are the example: (from here)
The out put of the code:
Here I will trace and try to explain how the codes work using my own words.
- scope_test is created
- Python read the 'scope_test()' and went back to read the info inside.
- do_local, do_nonlocal, do_global were created inside scope_test.
- variable 'spam' was assigned to an id address which refer to "test spam".
- went back to read do_local (line 2) after executing do_local() (line 11)
- created a spam " local spam" inside do_local. This spam was different from the previous spam! They had different id address.
- local spam only existed in the do_local function, so after the last line in do_local was read, the spam with "local spam" was erased.
- python jumped back to line 12, which print the given string plus the spam, which still refers to "test spam" since the local spam wasn't there anymore.
- went back to do_nonlocal after do_nonlocal was executed.
- the 'nonlocal spam' pushed spam one level out, meaning now there's a spam with an id address (different from test spam) that refers to "nonlocal spam". The nonlocal spam now exists in the whole scope_test function (line1-16). Test spam got replaced.
- python jumped back to line 14, printed the given string with the spam now refers to "nonlocal spam".
- read do_global() in line 15 and go back to the do_global function in line 7.
- 'global spam' pushed the spam out to global, meaning now there's a spam with another id which refers to "global spam" that exists in the whole frame. (line1-19)
- However, when python executed the print in line 16 and looked for the spam, it start looking from inside to outside (local -> nonlocal -> global -> built-in). This means that the "nonlocal spam" would be found first. So the spam that would be printed is "nonlocal spam".
- Python executed the last line in the frame, which print "In global scope:" plus the spam, which now refers to "global spam" since the "nonlocal spam" is only inside the scope_test function.
In conclusion: What happened inside the function stays inside the functions, unless defined otherwise.
No comments:
Post a Comment