[Tutor] constructors

Lloyd Kvam pythontutor@venix.com
Wed, 10 Apr 2002 08:22:40 -0400


I will clone an object before passing it on to a User Interface edit routine.
If the user presses CANCEL, I stick with the original.  If they exit with OK,
I keep the object with their changes.

Also note that Python supports an alternative way to have default values.  You
can define them at the class level.

 >>> class Person:
... 	name = "Not Specified"
... 	age = "Not Specified"
... 	
 >>> newguy = Person()
 >>> newguy.name
'Not Specified'
 >>> newguy.name = "Erik"
 >>> newguy.name
'Erik'
 >>> Person.name
'Not Specified'

I have found class level defaults very useful for classes that represent
database tables.  The class defaults can easily be built from information
provided by the database.

Erik Price wrote:

> 
> 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
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582