Copy constructor in python? Copy constructor in python? python python

Copy constructor in python?


I think you want the copy module

import copyx = copy.copy(y)        # make a shallow copy of yx = copy.deepcopy(y)    # make a deep copy of y

you can control copying in much the same way as you control pickle.


In python the copy constructor can be defined using default arguments. Lets say you want the normal constructor to run the function non_copy_constructor(self) and the copy constructor should run copy_constructor(self, orig). Then you can do the following:

class Foo:    def __init__(self, orig=None):        if orig is None:            self.non_copy_constructor()        else:            self.copy_constructor(orig)    def non_copy_constructor(self):        # do the non-copy constructor stuff    def copy_constructor(self, orig):        # do the copy constructora=Foo()  # this will call the non-copy constructorb=Foo(a) # this will call the copy constructor


A simple example of my usual implementation of a copy constructor:

import copyclass Foo:  def __init__(self, data):    self._data = data  @classmethod  def from_foo(cls, class_instance):    data = copy.deepcopy(class_instance._data) # if deepcopy is necessary    return cls(data)