Python 副本 : How to inherit the default copying behaviour?

标签 python copy

好吧……这可能是个愚蠢的问题……但我现在找不到答案!

我需要实现一个对象的复制,我希望复制它的所有属性,除了一两个我想完全控制复制的属性。

这是对象的标准复制行为:

>>> class test(object):
...     def __init__(self, arg):
...         self._a = arg
... 
>>> t = test(123999)
>>> t._a
123999
>>> tc = copy.copy(t)
>>> tc._a
123999

这基本上意味着所有的属性都被复制了。我想做的是以下列方式重新使用此行为:

>>> class test(object):
...     def __init__(self, arga, argb):
...         self._a = arga
...         self._b = argb
...
...     def __copy__(self):
...         obj_copy = copy.copy(self) #NOT POSSIBLE OF COURSE => infinite recursion
...         obj_copy._b = my_operation(obj_copy._b)
...         return obj_copy

我希望你明白我的意思:我想重新使用对象复制行为,但 Hook 我自己的操作。有没有一种干净的方法来做到这一点(无需执行 for attr_name in dir(self): ...)???

最佳答案

你可以这样做:

def __copy__(self):
    clone = copy.deepcopy(self)
    clone._b = some_op(clone._b)
    return clone

这会起作用,因为 deepcopy 避免了递归。来自python docs :

The deepcopy() function avoids these problems by: keeping a “memo” dictionary of objects already copied during the current copying pass; and letting user-defined classes override the copying operation or the set of components copied.

关于Python 副本 : How to inherit the default copying behaviour?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3253439/

相关文章:

python - 如何在django详细 View 中显示多个类别?

python - 长变量赋值推荐换行

python - 在Python中处理unicode转换

node.js - 使用 Grunt 将文件复制到项目外部的目录

c# - 如何在单击按钮时立即将 dataGridView 数据导出到 Excel?

python - Python 中的连续重复

python - 检测 ROI 中的人脸中心

javascript - 将文本从文本字段复制到文本区域+标签

Javascript 清理从 html 标签复制的数据

python - 如何使用python复制文件以及目录结构/路径?