Python - copy.deepcopy() doesn't work on copying local scope into global scope variable
下面是我最新项目的一部分代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import copy chg = None def change(obj): print("obj =", obj) chg = copy.deepcopy(obj) #chg = obj print("chg = obj =", chg) class B(): def __init__(self): setattr(self, 'example_member',"CHANGED!") self.configure() def configure(self): global chg change(self.example_member) print("chg on inside =", chg) b = B() print("print chg on global =", chg) |
因此,我希望全球
因此,我期望以下输出:
1 2 3 4 | obj = CHANGED! chg = obj = CHANGED! chg on inside = CHANGED! print chg on global = CHANGED! |
号
然而,令我惊讶的是,全局
1 2 3 4 | obj = CHANGED! chg = obj = CHANGED! chg on inside = None print chg on global = None |
那么,我需要做什么才能用本地范围的
您应该在
1 2 3 4 5 6 | def change(obj): global chi # <<<<< new line print("obj =", obj) chg = copy.deepcopy(obj) #chg = obj print("chg = obj =", chg) |
给予:
1 2 3 4 | obj = CHANGED! chg = obj = CHANGED! chg on inside = CHANGED! print chg on global = CHANGED! |
号
不过,最好避免使用这样的全局变量。