How does exec work with locals?

前端 未结 3 758
小鲜肉
小鲜肉 2020-11-22 07:13

I thought this would print 3, but it prints 1:

def f():
    a = 1
    exec(\"a = 3\")
    print(a)
3条回答
  •  [愿得一人]
    2020-11-22 07:43

    If you are inside a method, you can do so:

    class Thing():
        def __init__(self):
            exec('self.foo = 2')
    
    x = Thing()
    print(x.foo)
    

    You can read more about it here

提交回复
热议问题