changing the List's behaviour?
Heather Coppersmith
me at privacy.net
Wed Jul 30 11:55:51 EDT 2003
On Wed, 30 Jul 2003 17:36:12 +0200,
Peter Otten <__peter__ at web.de> wrote:
> Heather Coppersmith wrote:
>>> class DefaultList(list):
>>> def __init__(self, sequence=[], default=None):
> list.init(self, sequence)
>>
>> That's asking for trouble. That mutable default argument for
>> sequence is evaluated at class definition-time, and all instances
>> of DefaultList created without a sequence argument will end up
>> sharing one list.
>>
>> Do this instead:
>>
>> class DefaultList( list ):
>> def __init__( self, sequence = None, default = None ):
>> if sequence is None:
>> sequence = [ ]
>>
>>> list.__init__(self, sequence)
> I can see the trouble only if the sequence argument is used to initialize a
> member, e.g.
> def __init__(self, seq=[]):
> self.seq = seq # bad, multiple instances may share one list
> However, in the DefaultList case, sequence is never changed.
> So I don't see what can go wrong. Am I overlooking something?
> - Peter
Oops, my mistake. ;-)
Regards,
Heather
--
Heather Coppersmith
That's not right; that's not even wrong. -- Wolfgang Pauli
More information about the Python-list
mailing list