Data sticking around too long

CedricCicada at gmail.com CedricCicada at gmail.com
Wed Sep 6 21:55:59 CEST 2006


Greetings!

Here's my script:

########  start of script
class ScannerCommand:
    taskName = ''
    scanList = []

    def __init__(self):
        print "Creating a ScannerCommand object; list has " + \
              str(len(self.scanList)) + " objects."

class Scanner:
    def Read(self, data):
        command = ScannerCommand()
        command.scanList.append(data)
        return command

class Handler:
    def Process(self, dataList):
        print "Processing data"
        for data in dataList:
            print "   " + data
        print "Finished processing data."

if __name__ == '__main__':
    s = Scanner()
    count = 0
    for data in ["Zero", "One", "Two", "Three"]:
        command = s.Read(data)
        handler = Handler()
        handler.Process(command.scanList)
##############  End of script

Here's the result:

##########  Start of result
Processing data
   Zero
Finished processing data.
Creating a ScannerCommand object; list has 1 objects.
Processing data
   Zero
   One
Finished processing data.
Creating a ScannerCommand object; list has 2 objects.
Processing data
   Zero
   One
   Two
Finished processing data.
Creating a ScannerCommand object; list has 3 objects.
Processing data
   Zero
   One
   Two
   Three
Finished processing data.
################  End of result

I had expected to get "Zero" by itself, then "One" by itself, and so
on.

Why is the ScannerCommand object being created with a scanList that
contains the data that was in the previously created ScannerCommand
object?  And what do I have to do to ensure that the code that is run
when I call ScannerCommand() gives me an object with an empty scanList?

I am a C++ developer in a shop that uses some Python as well, and I
just ran across this behavior for the first time.  I believe it is due
to the difference between binding a variable to an object, as Python
does, and actually creating the variable, as a similar C++ application
would do.

Thank you very much.

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




More information about the Python-list mailing list