Python class and global vs local variables -
this question has answer here:
- python class scoping rules 2 answers
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:
- what happening here in each print() statement?
- 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:
- the global scope
- the function scope
- the class body
- 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
Post a Comment