繁体   English   中英

Python-copy.deepcopy()在将本地范围复制到全局范围变量上不起作用

[英]Python - copy.deepcopy() doesn't work on copying local scope into global scope variable

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

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

那么,我需要做些什么才能使用局部范围的obj / example_member对象值来进行全局chg 我是Python的新手,所以一些解释可能对我也很有帮助。 :)

您应该在change()函数中将chg声明为global ,否则为local。 函数内部对未在函数内声明为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!

但是,最好避免使用这样的全局变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM