[英]Python - copy.deepcopy() doesn't work on copying local scope into global scope variable
Below is a portion of code from my latest project. 以下是我最新项目中的一部分代码。
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)
So the thing is, I was expecting global chg
to changes it values from None
to obj
's value. 所以事实是,我期望全局
chg
将其值从None
更改为obj
的值。
So I was expecting below output : 所以我期待下面的输出:
obj = CHANGED!
chg = obj = CHANGED!
chg on inside = CHANGED!
print chg on global = CHANGED!
However, it came to my surprise that global chg
identifier doesn't change at all. 但是,令我惊讶的是,全局
chg
标识符完全没有改变。 Below is the output produces by above code. 下面是上面代码产生的输出。
obj = CHANGED!
chg = obj = CHANGED!
chg on inside = None
print chg on global = None
So what I need to do in order to do the global chg
with local scoped obj
/ example_member
object value? 那么,我需要做些什么才能使用局部范围的
obj
/ example_member
对象值来进行全局chg
? I'm new to Python so some explanation might as do good to me. 我是Python的新手,所以一些解释可能对我也很有帮助。 :)
:)
You should declare chg
as global
in the change()
function, otherwise it is local. 您应该在
change()
函数中将chg
声明为global
,否则为local。 An assignment inside a function to a name not declared as global
within the function defaults the new variable to local scope. 函数内部对未在函数内声明为
global
名称的名称的赋值会将新变量默认为局部范围。
def change(obj):
global chi # <<<<< new line
print("obj =", obj)
chg = copy.deepcopy(obj)
#chg = obj
print("chg = obj =", chg)
Gives: 给出:
obj = CHANGED!
chg = obj = CHANGED!
chg on inside = CHANGED!
print chg on global = CHANGED!
However it would be better to avoid using a global like this. 但是,最好避免使用这样的全局变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.