[Tutor] constructors
Erik Price
erikprice@mac.com
Wed, 10 Apr 2002 07:38:33 -0400
On Wednesday, April 10, 2002, at 03:25 AM, Danny Yoo wrote:
> copy.copy() or copy.deepcopy() should work pretty well with normal
> Python
> classes, and by defining a __copy__() function, we can control how
> functions are cloned off.
>
> For example:
>
>
> ###
>>>> class Person:
> ... def __init__(self, name):
> ... self.name = name
> ... def greet(self):
> ... print "Hello, my name is %s" % self.name
> ... def __copy__(self):
> ... return Person(self.name.replace('u', 'uu'))
> ...
>>>> import copy
>>>> star = Person("luke")
>>>> star.greet()
> Hello, my name is luke
>>>> cloned_star = copy.copy(star)
>>>> cloned_star.greet()
> Hello, my name is luuke
> ###
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?
Thank you,
Erik