I am having troubles understand how variable lookup and assignment are done in Python. I have a few lines of code here to make my question concrete.
class Test:
number = 0
def __init__(self):
self.number += 1
def main():
number = 2
def foo():
# This line errors. In this scenario, foo has a local var "number". I am trying to assign "number"
# in foo's scope with another var named "number", beloning to foo's outer scope. According to
# Python's LEGB rule, shouldn't the var "number" on right hand sign of the "number = number + 1"
# statement be read from foo's outer scope then assigned to var "number" in foo's scope?
# I konw I shouldn't have variables with the same name in inner and outer scopes. If the code in
# foo didn't workHow come the code in Test__init__, which is similar to the code in foo, work?
number = number + 1
foo()
print(number)
test = Test()
print(test.number)
main()