Copy constructor in python?

Solution 1:

I think you want the copy module

import copy

x = copy.copy(y)        # make a shallow copy of y
x = copy.deepcopy(y)    # make a deep copy of y

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

Solution 2:

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 constructor

a=Foo()  # this will call the non-copy constructor
b=Foo(a) # this will call the copy constructor

Solution 3:

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

import copy

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