[Tutor] constructors

Karthik Gurumurthy karthikg@aztec.soft.net
Wed, 10 Apr 2002 17:45:16 +0530


> From: Erik Price [mailto:erikprice@mac.com]
> I read the "copy" document you linked to, above, but it assumes a priori
> knowledge about cloning to some extent.  What it doesn't explain is
> -why- you would use cloning.  Karthik mentioned that it is similar to
> something done in Java, but I'm still a little confused about cloning --
> is it simply a "special" (two-underscores) method that you can use to
> flesh out an object instance and make it unique?  That's what the
> example above, with Luke and Luuke, seems to suggest.  Or is there more
> to it?

you would do cloning to achieve exactly what you wanted to..
ie get a new instance (ie clone the instance) of a class from an existing
one with all it's attributes copied.

Using the copy module happens to be a *standard* way of getting a copy in
python.
So a client who uses your class will call copy.deepcopy() to achieve it
since it is the norm.

You could very well give another method (say getCopy()) to do the same.
But then you w'd be required to educate the client about this new method!
which ideally you w'd'nt want to.

If you don't give an implementation of __copy__ (clone equivalent), copy
module would use
the default implementation. ie make a copy of all the attributes.

Next comes something called shallow copying. which i guess copy.copy() does.
Danny correct me! ..:-)..

But as Danny pointed out, you can give your own implementation of __copy__()
(which is what copy module
actually calls) and do something different.
In this case he does return another instance with a small change in the
attribute value.

     def __copy__(self):
         return Person(self.name.replace('u', 'uu'))


HTH,
karthik.