initialization of lists in classes

Adrian Eyre a.eyre at optichrome.com
Fri Oct 15 04:38:55 EDT 1999


>> class test:
>>     list = []
>>     float = 3.2
>> 
>>     def __init__(self):
>>         print 'list, float (#1):', self.list, self.float
>>         self.list.append(1,2)
>>         self.float = self.float + 2.0
>>         print 'list, float (#2):', self.list, self.float

> until you know exactly how class variables behave,
> make sure you initialize all your instance variables
> in the constructor instead:
> 
> class test:
>      def __init__(self):
>          self.list = []

The other one to be careful of is this:

class test:
    def __init__(self, list = []):
        self.list = list
        self.list.append(1,2)

Looks perfectly harmless, but:

>>> a=test()
>>> b=test()
>>> a.list
[(1, 2)]
>>> b.list
[(1, 2), (1, 2)]

--------------------------------------------
Adrian Eyre <mailto:a.eyre at optichrome.com>
Optichrome Computer Solutions Ltd
Maybury Road, Woking, Surrey, GU21 5HX, UK
Tel: +44 1483 740 233  Fax: +44 1483 760 644
http://www.optichrome.com 
--------------------------------------------





More information about the Python-list mailing list