Python class and global vs local variables -


this question has answer here:

i have problem understanding happening outcome of following pieces of code:

my_str = "outside func" def func():     my_str = "inside func"     class c():         print(my_str)         print((lambda:my_str)())         my_str = "inside c"         print(my_str) 

the output is:

outside func inside func inside c 

another piece of code is:

my_str = "not in class" class c:     my_str = "in class"     print([my_str in (1,2)])     print(list(my_str in (1,2))) 

the output is:

[‘in class’, 'in class’] ['not in class’, 'not in class’] 

the question is:

  1. what happening here in each print() statement?
  2. can explain why print() statement string different namespaces?

edit 1:

i think different this question because humbly think answers there not explain variation:

my_str = "outside func" def func():     my_str = "inside func"     class c():         print(my_str)         print((lambda:my_str)())        #my_str = "inside c"         print(my_str) 

the output is:

inside func inside func inside func 

edit 2:

indeed, duplicate this question because martijn pieters says:

the answer there states: if name assigned within class body, @ start. assigned my_str, making same case y there. commenting out line means no longer assigning my_str, making same case x.


there 4 scopes here:

  1. the global scope
  2. the function scope
  3. the class body
  4. the lambda scope

when creating class statement, class body executed function , local namespace of 'function' used class attributes.

however, class body not scope, , such behaves differently functions. in function body, binding defines scope; assign name in function , marked local. in class, assigning name makes global until assignment.

so first print() call finds my_str global, because later in class body bind name. consequence of class bodies not taking part in scopes.

next, define lambda , call it. my_str never assigned in lambda has found in parent scope. here class body not scope, , next scope function scope. why line prints inside func.

last, assign local name my_str in class body, , print local.

the moment remove assignment, names in class treated non-local; first , last print() statements equal, , name looked according normal scoping rules.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -