initializing mutable class attributes
dperl at rogers.com
Mon Aug 30 07:39:53 CEST 2004
There is something with initializing mutable class attributes that I am
struggling with. I'll use an example to explain:
attr1=None # this is OK
attr2=[ ] # this is wrong
def foo(self, data):
The initialization of attr1 is obviously OK, all instances of Father
redefine it in the method foo. But the initialization of attr2 is wrong
because all the instances of Father end up sharing the same value. Maybe
that is desired sometimes, but usually it is just a bug.
So the only solution I see to this is to initialize attr2 in __init__:
This is already awkward because there is such a difference between attr1 and
attr2. But moreover, I think this forces subclasses of Father to do
something like this:
class Child (Father):
I find this even more awkward because many people will forget to do it.
Clearly, this is then a more general issue with __init__, but I think it is
accentuated by the fact that you HAVE TO HAVE __init__ in order to
initialize attributes that are mutable.
Is there something I don't know here and there is a better way to do this in
Python? I would like to get a better solution or otherwise start a
More information about the Python-list