initialization of lists in classes
Fredrik Lundh
fredrik at pythonware.com
Fri Oct 15 04:05:36 EDT 1999
Balint Aradi <ab007 at hszk.bme.hu> wrote:
> I would like to ask something about initialization of lists in
> classes. Given the Python code
>
> 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
list is a shared class variable, not an instance variable.
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 = []
self.float = 3.2
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
iirc, the FAQ has more info on class variables
and other issues related to shared mutable
variables.
</F>
coming soon:
http://www.pythonware.com/people/fredrik/librarybook.htm
More information about the Python-list
mailing list