包含自动更改的对象的 Python 堆栈

标签 python stack

我在 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/

相关文章:

python - virtualenv 使用 Python 2.6 而不是 2.7

python - 在 Cython 中将复杂的 numpy 数组传递给 C++

c - C 标准是否对使用的堆栈空间量有任何保证?

c - "STACK"之前的预期表达式错误

c - 如何比较链表中的条目?

python - 在 Python 中使用堆栈

python - 从 7.1.2 安装 pip 8.1.1 时出现问题

python - pykinect2深度帧被截断

python - 如何在 telebot(pytelegramBotAPI)中获取 chat_id 和 message_id 以更新 Telegram bot(Python)中最后发送的消息

Java - 如何编写一种方法将一个堆栈反转到另一个堆栈而不破坏原始堆栈?