How to copy instances of a custom defined class in Python 3.3? -
i trying copy instances of custom class in python 3.3, similar how dict.copy()
, list.copy()
work. how go this?
here example of custom class:
class customclass(object): # custom class example def __init__(self, thing): self.thing = thing
in general, can use copy
module produce copies of python objects.
copy.copy()
produce shallow copy; new instance created attributes copied over. if of attributes mutable , mutate objects you'll see changes reflected on both objects.copy.deepcopy()
produce copy recursively; mutable objects cloned.
if class implements __copy__
method it'll used create shallow copy of object; return new instance attributes copied on , altered needed.
similarly, can implement __deepcopy__
method implement custom deep copy method; it'll passed memo
state, pass on recursive copy.deepcopy()
calls.
note cannot use copy class object however. classes meant singletons; don't need create copy in case. can use subclassing instead, or class factory function, produce distinct class objects.
Comments
Post a Comment