Python copy:如何继承默认复制行为? [英] Python copy : How to inherit the default copying behaviour?

查看:178
本文介绍了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 =>无限递归
... obj_copy._b = my_operation(obj_copy._b)
... return obj_copy

我希望你知道点:我想重用对象复制行为,但钩住我自己的操作。是否有一个干净的方式来做到这一点(不必在 c>

$ <

  def __copy __(self) :
clone = copy.deepcopy(self)
clone._b = some_op(clone._b)
返回clone

这将工作,因为 deepcopy 避免递归。从 python文档


deepcopy()函数通过以下方式避免了这些问题:
保持在当前复制过程中已经复制的对象的memo字典;和
让用户定义的类重写复制操作或复制的组件集。



Ok ... It might be a stupid question ... but I'm not finding the answer right now !

I need to realize the copy of an object, for which I want all the attributes to be copied, except one or two for which I want to fully control the copy.

Here is the standard copying behaviour for an object :

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

Which basically means that all the attributes are copied. What I would like to do is re-use this behaviour in the following way :

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

I hope you got the point : I want to re-use the object copying behaviour, but hook-in my own operations. Is there a clean way to do this (without having to do for attr_name in dir(self): ...) ???

解决方案

You could just do:

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

This will work because deepcopy avoids recursion. From the 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 copy:如何继承默认复制行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆