[Tutor] constructors

Kirby Urner urnerk@qwest.net
Wed, 10 Apr 2002 21:22:57 -0400


On Thursday 11 April 2002 12:06 am, Erik Price wrote:

> I'm curious why you couldn't just assign a new reference to the object
> to get a copy.  OR.... would the new reference point to the SAME
> instance?  I just thought of this possibility now, as I wrote this.  Is
> that why you would want to copy an instance with this technique?
>

That's right -- new reference would point to same object, not
a copy.

> This technique of using class level defaults seems better than using
> default arguments to the constructor, since you can do something more
> complex to define the variables (like pull data from a database and use
> that as the defaults).  I haven't seen this before in Python -- in fact,
> I've only ever seen methods as part of a class, never standalone
> variables like this.
>

You still need to provide a way to change class level defaults on
a per instance basis, so if you don't provide this in the constructor,
some other method will need to shoulder the burden.  

Class variables are shared across all instances, and may still be
accessed even if self.property has been reset in a given instance, 
by referencing [the class].property, e.g.:

  class Foo:
      prop1 = "Test"
      def __init__(self, prop1=None):
	if prop1:
	    self.prop1 = prop1

 >>> myobj = Foo("Hello")
 >>> myobj.prop1
 "Hello"
 >>> Foo.prop1
 "Test"

You can change the class-level properties at runtime, meaning all new
instances will get the new default, and old instances will have a new
class-level value as well (which may not matter, if it was reset).

 >>> Foo.prop1 = "world"
 >>> myobj.__class__
 <class __main__.Foo at 0x828137c>
 >>> myobj.__class__.prop1
 'world'
 >>> newobj = Foo()
 >>> newobj.prop1
 'world'

Kirby