Python copy : How to inherit the default copying behaviour?

旧城冷巷雨未停 提交于 2019-12-12 11:22:50

问题


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): ...) ???


回答1:


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.




回答2:


If you don't have properties &c, all the state is in the __dict__, so...:

...     def __copy__(self):
...         obj_copy = object.__new__(type(self))
...         obj_copy.__dict__ = self.__dict__.copy()
...         obj_copy._b = my_operation(obj_copy._b)
...         return obj_copy



回答3:


I would like to do this in the following way - try it:

import copy
class test(object):
    def __init__(self, **args):
        self.args = args

    def __copy__(self):
        obj_copy = copy.deepcopy(self)
        return obj_copy 


来源:https://stackoverflow.com/questions/3253439/python-copy-how-to-inherit-the-default-copying-behaviour

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!