I am wondering why a method of a class doesn't look into its enclosing scope, if a name is not defined.
def test_scope_function():
var = 5
def print_var():
print(var) # finds var from __test_scope_function__
print_var()
globalvar = 5
class TestScopeGlobal:
var = globalvar # finds globalvar from __main__
@staticmethod
def print_var():
print(TestScopeGlobal.var)
class TestScopeClass():
var = 5
@staticmethod
def print_var():
print(var) # Not finding var, raises NameError
test_scope_function()
TestScopeGlobal.print_var()
TestScopeClass.print_var()
I would expect TestScopeClass.print_var()
to print 5
since it can read classvar
in the TestScopeClass
body.
Why this behavior? And what should i read in the docs to get to know about it.