python - 在 python 中的自定义对象上使用 __deepcopy__?

标签 python class object deep-copy

我正在编写一个使用 list 作为复合属性的自定义 Queue 类。我不从列表中继承。我的代码在这里。我收到下面粘贴的 deepcopy 错误。有人可以帮我解决我出了什么问题吗?谢谢

from iterator import Iterator
class Abstractstruc(object):
    def __init__(self):
        assert False
    def __str__(self):
        return "<%s: %s>" %(self.__class__.__name__,self.container)

class Queue(Abstractstruc,Iterator):

    def __init__(self,value=[]):
        self.container=[]
        self.size=0
        self.concat(value)

    def add(self, data):
            self.container.append(data)

    def  remove(self):
        self.container.pop(0)


    def peek(self):
        return self.container[0]


    def __getitem__(self,index):
        return self.container[index]


    def __iter__(self):
        return Iterator(self.container)

    def concat(self,value):
        for i in value:
            self.add(i)

    def __bool__(self):
        return len(self.container)>0

    def __len__(self):
        return len(self.container)


    def __deepcopy__(self,memo):
        return Queue(copy.deepcopy(self.container,memo))


if __name__=='__main__':
    q3=Queue()

    li=[1,2,3]
    q3.add(li)
    print q3 
    print len(q3)

    q4=copy.deepcopy(q3)
    q3.peek()[0]=100


    print "after modifying"
    print q3
    print "q4 = ", q4

输出:

<Queue: [[1, 2, 3]]>
1
Traceback (most recent call last):
  File "test.py", line 56, in <module>
    q4=copy.deepcopy(q3)
NameError: name 'copy' is not defined

最佳答案

您需要导入 copy module :

import copy

错误信息:

Traceback (most recent call last):
  File "test.py", line 56, in <module>
    q4=copy.deepcopy(q3)
NameError: name 'copy' is not defined

NameError 在 Python 不知道裸名 copy 指的是什么时引发。

关于python - 在 python 中的自定义对象上使用 __deepcopy__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20201673/

相关文章:

python - 如何正确解析右括号

python - 如何在 return 语句中调用另一个本地函数内的本地函数?

python - 在 HTML 源中找不到该属性,但 Python 程序运行正常

C++,处理多个构造函数重载和冗余代码

php - 命名空间 autoloading_register 未捕获错误 : class cannot be found

python - 如何在python中没有分隔符的数字字符串中查找缺失的数字?

java - 为什么这个 java 代码没有在 Eclipse IDE 上显示。公共(public)类型App必须在自己的文件中定义

javascript - 如何改变一个对象的各级键的值?

python - 在 __init__ 内部,使用 __init__ 外部的变量

javascript - 在 Javascript 中创建过多音频对象时浏览器崩溃