initialization of lists in classes

Mark Nottingham mnot at pobox.com
Fri Oct 15 04:06:59 EDT 1999


Try:

class test:
    def __init__(self):
        self.list = []
        self.float = 3.2
        print "list, float (#1):', self.list, self.float

and so on...


Balint Aradi <ab007 at hszk.bme.hu> wrote in message
news:Pine.GSO.4.10.9910150904020.2553-100000 at ural2...
Hi,

  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

print 'a:'
a=test()
print 'b:'
b=test()


I get the result

a:
list, float (#1): [] 3.2
list, float (#2): [(1, 2)] 5.2
b:
list, float (#1): [(1, 2)] 3.2
list, float (#2): [(1, 2), (1, 2)] 5.2


 I don't understand the mechanism behind that. Why is b.list initialized
with the value of a.list? (Or why isn't b.float initialized with the value
of a.float?)  I'm quite a newbie in Python, so this was probably a stupid
question, but can anyone explain that to me?

Thanks a lot,


   Bálint


Ps. I'm using: Python 1.5.1 (#1, Dec 17 1998, 20:58:15)  [GCC 2.7.2.3] on
linux2




--
http://www.python.org/mailman/listinfo/python-list







More information about the Python-list mailing list