6

I'm reviewing some old python code and came accross this 'pattern' frequently:

class Foo(object):
    def __init__(self, other = None):
        if other:
            self.__dict__ = dict(other.__dict__)

Is this how a copy constructor is typically implemented in Python?

Homunculus Reticulli
  • 60,275
  • 77
  • 205
  • 314

2 Answers2

5

Note that the attributes aren't copied, they are shared.

>>> a = Foo()
>>> a.x=[1,2,3]
>>> b = Foo(a)
>>> b.x[2] = 4
>>> a.x
[1, 2, 4]
Reinstate Monica
  • 4,444
  • 1
  • 23
  • 34
4

This is a way to copy all attributes from one object to another one. However note that:

  • The object passed to the __init__ method may have any type (not the same type as the object being created).
  • Only object attributes are copied (class attributes and methods are not).
jcollado
  • 37,681
  • 8
  • 99
  • 131