Creating Class Objects in Loop
John Nagle
nagle at animats.com
Mon Mar 31 00:34:00 EDT 2008
Fish wrote:
> Hello Folks,
> I am reading a CSV file and based on that I am creating TestCase(my
> own defined class) objects in a for loop. The problem is each time I
> create a new TestCase object in loop, previous objects data is already
> copied in that object.
What's actually happening to you is that you've run into one of the
dumber features of Python - default values for parameters which are
mutable, like lists, result in rather unexpected behavior. The
problem is that
def __init__(self, pcap = None, sids = []):
creates the empty list "[]" once at startup, and that list is
persistent across calls to __init__. Yes, that's wierd, but
Python does that for historical reasons.
Actually, you can write your main loop much more simply:
def returnTcLst(path):
fp = open(path)
for line in fp:
fields = line.split(",") # split into list at commas
fields = map(lambda(s) : s.strip(), fields) # strip whitespace
tcLst.append(TestCase(fields[0], fields[1:])) # pcap, then sids
John Nagle
More information about the Python-list
mailing list