0

I'm currently working something on python and this is the simplified version of which where I'm having trouble with.

class test:
    def a_0(self):
        return 0
    def a_1(self):
        return 1
    def a_2(self):
        return 2
    def a_3(self):
        return 3
    

a = test()
def x():
    for i in range(3):
        print(f"s={a.a_0()}")
        exec(f"s={a.a_0()}")
        
        print(locals())
        print(s)

x()

So what I'm doing is getting a value from the instance a, and assigning it to another variable by using "exec".

The things is that when I execute this code, I get s = 0 // result of print(f"s={a.a_0()}") {'i': 0, 's': 0} // result of print(locals()) So from the second result, I can see that s is assigned to 0 on local but after this gives

NameError: name 's' is not defined // result of print(s)

I have no idea why this NameError occurs..

K C
  • 39
  • 3

0 Answers0