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?
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?
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.