[ Python ] 如何自定义私有变量的作用域

https://www.cnblogs.com/yeungchie/

code

class let:

    def __enter__(self):
        self.var_bk = {}
        self.var_bk.update(globals())

    def __exit__(self, type, value, trace):
        globals().clear()
        globals().update(self.var_bk)

test

a = 1

with let():
    a = 2
    print(a)
    # 2

print(a)
# 1
posted @ 2024-01-06 05:55  YEUNGCHIE  阅读(82)  评论(0编辑  收藏  举报