我在 Python 中使用了以下堆栈类来存储另一个类的对象。
class Stack :
def __init__(self) :
self.items = []
def push(self, item) :
self.items.append(item)
def pop(self) :
return self.items.pop()
def isEmpty(self) :
return (self.items == [])
scopeStack=Stack();
object1=AnotherClass();
object1.value=2;
scopeStack.push(object1);
在堆栈外更改对象 object1 的内容时,堆栈对象的内容也会更改。
object1.value=3;
obj=scopeStack.pop();
print obj.value; #gives output 3
我应该怎么做才能在局部变量和堆栈的内部变量之间没有这种动态绑定(bind)?
最佳答案
查看 copy
模块发现 here .您要查找的内容称为 copy.deepcopy()
。
例子:
class Obj:
def __init__(self, value):
self.value = value
x = Obj(5)
y = copy.deepcopy(x)
print 'x:', x.value
print 'y:', y.value
x.value = 3
print 'x:', x.value
print 'y:', y.value
输出:
x: 5
y: 5
x: 3
y: 5
关于包含自动更改的对象的 Python 堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14972836/