[Tutor] constructors

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 10 Apr 2002 00:25:01 -0700 (PDT)


> coming from a java background, there is a concept of cloning to do the
> copying part.
> I guess it's there in most OO languages ( i guess it the copy constructor in
> C++ ?? and so on...)
> It c'd be as simple as having a method clone() on your Person class to do
> it, the way it is in java.
> It just fills up another instance with the current Person's attributes and
> w'd return that.
>
> typically used as
>
>  p1 = person(name="abc")
>  p2 = p1.clone()
>
> am not sure if this is considered a good practice in Python too.

Yes the 'copy' module actually allows us to do what Java's clone() does:

    http://www.python.org/doc/lib/module-copy.html


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
###


May the force be with you.