5
a = 0
b = 0
def test():
    a = 1
    b = 1

    class Test:
        print(a, b)
        a = 2
test()

It gives

0 1

It should be

1 1

Why is this happening?

Boann
  • 48,794
  • 16
  • 117
  • 146
ParthS007
  • 2,581
  • 1
  • 22
  • 37
  • I am not sure either but when I use `nonlocal a` and `nonlocal b` within `Test` it outputs `1,1`. Hopefully someone can explain why. – yudhiesh Jan 27 '21 at 06:42
  • 4
    Does this answer your question? [Weird scoping behavior in python](https://stackoverflow.com/questions/64974078/weird-scoping-behavior-in-python) – Tsubasa Jan 27 '21 at 06:44

1 Answers1

0

Inside the test function, you're not actually initializing a new Test object, so Python will read through the class definition to use it inside the function scope, so it does execute the print statement. The problem is that you are trying to change the value of a in the class scope and this generates that a take the previous value of a outside the function definition.