Python copy : How to inherit the default copying behaviour?
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 h开发者_如何学运维ook-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.
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
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
精彩评论