Python - copy.deepcopy()不能将局部范围复制到全局范围变量中

时间:2016-11-05 07:43:37

标签: python python-3.x

以下是我最新项目的部分代码。

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)

事实是,我期待全球chg将其值从None更改为obj的值。

所以我期待低于输出:

obj = CHANGED!
chg = obj = CHANGED!
chg on inside = CHANGED!
print chg on global = CHANGED!

然而,令我惊讶的是,全局chg标识符根本没有变化。下面是上面代码产生的输出。

obj = CHANGED!
chg = obj = CHANGED!
chg on inside = None
print chg on global = None

那么我需要做些什么才能使用本地范围的chg / obj对象值来执行全局example_member?我是Python的新手,所以一些解释可能对我有好处。 :)

1 个答案:

答案 0 :(得分:2)

您应该在chg函数中将global声明为change(),否则它是本地的。函数内部的赋值给函数中未声明为global 的名称将新变量默认为局部范围。

def change(obj):
    global chi                       # <<<<< new line
    print("obj =", obj)
    chg = copy.deepcopy(obj)
    #chg = obj
    print("chg = obj =", chg)

给出:

obj = CHANGED!
chg = obj = CHANGED!
chg on inside = CHANGED!
print chg on global = CHANGED!

然而,最好避免使用像这样的全局。