Class warfare...

Warren Focke wfocke at
Fri Sep 15 19:13:54 CEST 2000

Larry Whitley:

> I suspect that my [Bucket()] is producing a reference to the class
> rather to an object that is an instance of the class.

The call to Bucket is returning a reference to an instance.  When you
multiply the list by 5, it produces 5 copies of that reference rather
than making 5 calls to Bucket.  A copy of a reference points to the same
object as the original reference.  So in your case, you have 5 slots in
the list, but they all contain the same bucket.

If the Bucket call had produced a reference to the class rather than an
instance, you wouldn't have been able to access cnt, since the class
doesn't have that attribute.

Warren Focke


If you had made the class completely different:

class Pail:
      cnt = 0

you would be able to access cnt via the class itself (Pail.cnt) as well
as via an instance of the class.  In that case, newly created pails
would not contain a cnt of their own, but would inherit the class's cnt.
After assignment through an instance, the instance would have its own
cnt, which would be seen by accesses through that instance in preference
to the class's cnt:

>>> p = Pail()
>>> q = Pail()
>>> Pail.cnt
>>> p.cnt
>>> q.cnt
>>> p.cnt = 1
>>> p.cnt
>>> q.cnt

You could assign a new value to the class attribute, and then any
instances which had not had their cnt changed (ones that had been
created already as well as ones created afterwards) would appear to have
the new value, while the cnt of instances which had had theirs changed
would retain their own value:

>>> Pail.cnt = 5
>>> q.cnt
>>> p.cnt

Whether such behavior is desirable is another question.  Empty pails
would use a bit less memory than empty buckets, so if you were making a
lot of the things and never changing most of them, pails would be more
Just because romance and rapture have so often served as a pretext for
curdled banality doesn't make the sentiments themselves obsolete.
 -- Michelle Goldberg

More information about the Python-list mailing list