How to 'declare' class attributes?

Martijn Faassen m.faassen at vet.uu.nl
Sat May 26 20:46:17 EDT 2001


Rainer Deyke <root at rainerdeyke.com> wrote:
> "Alex Martelli" <aleaxit at yahoo.com> wrote in message
> news:9eoq8d0i27 at enews2.newsguy.com...
[snip]
>> Solutions 1 and 2 address completely different problems, so
>> how can they be better/worse than each other...?

> No they don't.  So long as the attributes are not mutable objects, they can
> both solve the same problem.  Consider:

> class Counter0:
>   count = 0
>   def __call__(self):
>     self.count = self.count + 1
>     return self.count

> class Counter1:
>   def __init__(self):
>     self.count = 0
>   def __call__(self):
>     self.count = self.count + 1
>     return self.count

> An instance of class 'Counter0' is identical in external behavior to an
> instance of 'Counter1'.

And if you use class attributes in such an immutable way (they don't need
to be immutable as long as you simply don't change them), they can have
some advantages; in the previous example Counter0 instances have no
memory in use for the count attribute until they are actually called,
in the second they do. There may therefore be a slight memory advantage
(though slower in execution) in some circumstances.

This type of thing can be useful in case of 'defaults' in an inheritance
hierarchy; the base class has a class attribute which lists the default
value, and subclasses and/or their instances of them may start doing interesting
things with that attribute. As long as you don't assign to the attribute,
the behavior is similar to that of methods, and as soon as you assign
to the attribute in fact a new attribute is created in the instance,
so it doesn't bother any other instances.

This type of behavior seems especially useful in circumstances where
you need to handle object schema evolution, like in the ZODB.

Regards,

Martijn
-- 
History of the 20th Century: WW1, WW2, WW3?
No, WWW -- Could we be going in the right direction?



More information about the Python-list mailing list