How to 'declare' class attributes?

Alex Martelli aleaxit at yahoo.com
Sat May 26 17:31:29 EDT 2001


"Rainer Deyke" <root at rainerdeyke.com> wrote in message
news:rMUP6.25924$CD5.13722470 at news2.rdc2.tx.home.com...
    ...
> 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'.

Not really: try accessing theinstance.__class__.count (and this IS
external behavior...) -- it will succeed in one case, give an exception
in the other.  Still, you can make your assertion true by changing
all occurrences of 'count' into '__count' in both classes (I don't...
count... THAT as 'external' behavior...).

In the very special cases where the two kinds of initialization are
equivalent ('private' variables, referring to immutable objects) it
seems to me that the principle of least surprise (for attributes
that are re-bound on a per-instance basis) is best served by
using __init__ to always bind the attributes per-instance.


Alex






More information about the Python-list mailing list