【问题标题】:Python stack containing objects changing automatically包含自动更改对象的 Python 堆栈
【发布时间】:2013-02-05 00:57:51
【问题描述】:

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

我应该怎么做才能在局部变量和堆栈的内部变量之间没有这种动态绑定?

【问题讨论】:

  • 您希望 Python 如何克隆任意对象?
  • 那我应该怎么做才能在 Python 中有这样的东西呢?
  • 你可以尝试使用deepcopy

标签: python stack


【解决方案1】:

查看找到herecopy 模块。您要查找的内容称为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    

【讨论】:

    【解决方案2】:

    如果您想要对象的副本,则需要复制或深度复制对象。查看copy 模块。

    【讨论】:

      【解决方案3】:

      它不是动态绑定,它只是对同一个对象的多个引用。当您执行scopeStack.push(object1) 时,您将该对象压入堆栈——不是对象的名称或对象的内容,而是对象本身。如果您稍后修改该对象,其修改将显示在任何引用它的地方。

      如果你希望栈上的版本是独立的,那么你需要制作一个副本并推送副本。您可以尝试为此使用copy 模块,但如果您的对象是自定义类的实例,您可能需要为该类编写自己的复制机制。 Python 无法自动知道如何复制您创建的任何自定义类的实例。

      【讨论】:

      • 我是 Python 新手,我曾经在 Java 和 C++ 中这样做过。这是一个自定义类。我应该如何为此制作一个复制模块?我可以有这样一个库堆栈来满足我的目的吗?
      • the documentation 中针对copy 模块所述,您可以使用__copy____deepcopy__ 方法。但是,如果您的对象只是 Python 内置类型的简单集合,copy.deepcopy 可能开箱即用。
      • 谢谢!我会查一下。
      猜你喜欢
      • 2015-10-22
      • 2020-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-26
      • 2018-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多