Data sticking around too long

CedricCicada at gmail.com CedricCicada at gmail.com
Wed Sep 6 16:46:32 EDT 2006


Skip and Matimus,

Thank you for your replies.  Putting initialization in the constructor
gets me what I want.  But I'd like to understand this a bit more.
Here's another script:

class ScannerCommand:
    taskName = ''
    scanList = []

    def __init__(self, data):
        self.scanList = []
        self.scanList.append(data)

if __name__ == '__main__':
    c1 = ScannerCommand("c1")
    c2 = ScannerCommand("c2")
    print "C1: "
    for data in c1.scanList:
        print "   " + data
    print "C2: "
    for data in c2.scanList:
        print "   " + data

And here's the output, which is what I want:
C1:
   c1
C2:
   c2

If scanList is a class variable shared between all instances of the
class, then C1's list should have held "C2" when I printed it, since C2
came along and changed scanList.  But obviously, here it's not a class
variable and the two instances have their own lists.

If I don't initialize scanList in the constructor, then scanList is a
class variable (in C++, it would be a static member of the class) that
is shared among all instances of the class.  If I do initialize
scanList in the constructor, then scanList magically becomes an
instance variable, with every instance of the ScannerCommand object
having its own scanList list???  Is that really the way it works?  I
would have thought the C++ way, with some special syntax to distinguish
a class variable from an instance variable, would be much easier to
work with.

Thanks again!

Rob Richardson
RAD-CON, Inc.
Bay Village, OH




More information about the Python-list mailing list