Creating Class Objects in Loop
Fish
abbas4u at gmail.com
Sun Mar 30 18:59:14 EDT 2008
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.
e.g. my sample CSV file is
# -------------------------
hello.pcap, 123, 231
test.pcap, 90, 899
hello2.pcap, 81, 18
# -----------------------
When I print the TestCase elements from returned list I get
(Pdb) print tcLstOrig[0]
Pcap Path: hello.pcap
Sid List: 123, 231, 90, 899, 81, 18,
(Pdb) print tcLstOrig[1]
Pcap Path: test.pcap
Sid List: 123, 231, 90, 899, 81, 18,
(Pdb) print tcLstOrig[2]
Pcap Path: hello2.pcap
Sid List: 123, 231, 90, 899, 81, 18,
Kindly guys advise me on this thing. Function snippet and Class
definition are provided below.
Regards,
Fish
======= Problem Code
The function snippet reading CSV and creating TestCase objects is
[code]
tcLst = []
# CSV file is read in variable 'lines'
def returnTcLst(path):
fp = open(path)
lines = fp.readlines()
for line in lines:
tc = TestCase()
i = line.find(",")
tc.setPcap(line[:i].strip())
line = line[i+1:]
line = line + ","
i = line.find(",")
while i != -1:
sid = line[:i].strip()
tc.appendSid(sid)
line = line[i+1:]
i = line.find(",")
tcLst.append(tc)
del tc
return tcLst
[/code]
My TestCase Class is defined as
[code]
class TestCase(object):
def __init__(self, pcap = None, sids = []):
self.__Pcap = pcap
self.__lstSid = sids
def setPcap(self, path):
self.__Pcap = path
def appendSid(self, sid):
self.__lstSid.append(sid)
def __str__(self):
text = "Pcap Path: " + self.__Pcap + "\n"
text += "Sid List: "
for sid in self.__lstSid:
text += sid + ", "
text += "\n"
return text
[/code]
More information about the Python-list
mailing list