Copy construction of class instance object

Steven Taschuk staschuk at telusplanet.net
Wed May 28 12:24:08 EDT 2003


Quoth Bror Johansson:
> Is there a good/recommended way to emulate the copy constructor
> classinstance creation (a la C++) in Python?

Why do you want to?

If memory serves (and I haven't used C++ in quite a while, so it
might not), the copy constructor is used when you do, for example,
    Foo a;
    Foo b = Foo("args", "to", "normal", "constructor");
    a = b;
Then a and b are different objects, the one in a having been
created by the copy constructor.

If this is the behaviour you want, there's no sane way to do it in
Python, because what assignment means in Python is almost but not
quite completely unlike assignment in C(++).  The analogous Python
code
    b = Foo('args', 'to', '__init__')
    a = b
will never create a copy of b; always a and b will end up
referring to the same object.  If you want a copy, ask for one:
    import copy
    b = Foo('args', 'to', '__init__')
    a = copy.deepcopy(b)
or some such.

(It would be possible to play tricks with properties or
__setattr__, e.g.,
    import copy
    class CopyHolder(object):
        def set_copy(self, value):
            self._copy = copy.deepcopy(value)
        copy = property(lambda self: self._copy, set_copy)
    a = [1, 2, 3]
    x = CopyHolder()
    x.copy = a
    print 'x.copy is a:', (x.copy is a)
    a[2] = 4
    print 'a:', a
    print 'x.copy:', x.copy
prints
    x.copy is a: 0
    a: [1, 2, 4]
    x.copy: [1, 2, 3]
But this would be highly strange and unreadable.)

-- 
Steven Taschuk              Aral: "Confusion to the enemy, boy."
staschuk at telusplanet.net    Mark: "Turn-about is fair play, sir."
                             -- _Mirror Dance_, Lois McMaster Bujold





More information about the Python-list mailing list