如何定义一个函数来自动复制 class 并在没有输入参数的情况下删除它们?
How to define a function to automatically copy a class and delete them without input argument?
有一个python模块module1.py,在这个模块里面有一个class1,一个定义为x=class1()和y=的变量class1()。经过几次操作,对象 x 包含数据。
如何在模块 1 中编写函数 clean_up() 使得
module1.clean_up() #takes no input argument
会将 x 重置为空的 class1() 并使 y 包含 x 的值?
我试过使用
def clean_up():
y=copy(x);
del x;
x=class1();
但是,这不会复制 x 并将其传递给 y,也不会 运行 成功并清除 x。
错误返回为
module1.clean_up()
UnboundLocalError: local variable 'Hecke_variable' referenced before assignment
即x 和 y 都被视为局部变量。
但在之前的 post、、class 中是可变的,函数内部对 class 实例的任何更改也会反映在函数外部。
为什么函数 clean_up() 运行 没有成功? clean_up()怎么写?
函数中定义的变量绑定到该函数的局部范围。如果您希望影响外部作用域中的变量,您需要使用 global 关键字让 python 知道。
def clean_up():
import copy
global x, y
y = copy.deepcopy(x)
x = Class1()
有一个python模块module1.py,在这个模块里面有一个class1,一个定义为x=class1()和y=的变量class1()。经过几次操作,对象 x 包含数据。
如何在模块 1 中编写函数 clean_up() 使得
module1.clean_up() #takes no input argument
会将 x 重置为空的 class1() 并使 y 包含 x 的值? 我试过使用
def clean_up():
y=copy(x);
del x;
x=class1();
但是,这不会复制 x 并将其传递给 y,也不会 运行 成功并清除 x。 错误返回为
module1.clean_up()
UnboundLocalError: local variable 'Hecke_variable' referenced before assignment
即x 和 y 都被视为局部变量。
但在之前的 post、
为什么函数 clean_up() 运行 没有成功? clean_up()怎么写?
函数中定义的变量绑定到该函数的局部范围。如果您希望影响外部作用域中的变量,您需要使用 global 关键字让 python 知道。
def clean_up():
import copy
global x, y
y = copy.deepcopy(x)
x = Class1()