Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the equivalent of a copy constructor in Python?

Tags:

python

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?

like image 479
Homunculus Reticulli Avatar asked Feb 03 '12 16:02

Homunculus Reticulli


1 Answers

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]
like image 140
Reinstate Monica Avatar answered Sep 28 '22 10:09

Reinstate Monica