Creating Class Objects in Loop

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun Mar 30 19:36:53 EDT 2008


En Sun, 30 Mar 2008 19:59:14 -0300, Fish <abbas4u at gmail.com> escribió:

> 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.

See this FAQ entry:  
http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects

> ======= Problem Code
>
> The function snippet reading CSV and creating TestCase objects is
> [code]
> tcLst = []
> # CSV file is read in variable 'lines'

Try to use the standard csv module instead; it's fairly easy.

> def returnTcLst(path):
>   fp = open(path)
>   lines = fp.readlines()
>   for line in lines:

Instead of those two lines, you could use:

     for line in fp:

(readlines() has to read the whole file into memory; files are their own  
line iterators)

> 	tc.setPcap(line[:i].strip())

getters/setters are not usually used in Python because they offer no  
advantage over directly using an attribute:

         tc.pcap = line[:i].strip()

> 	tcLst.append(tc)
> 	del tc

Why "del tc"?
That doesn't invoke the destructor, just removes the name "tc" from the  
local namespace. (The object tc refers to isn't destroyed yet because it  
has at least one reference: it's contained in the tcLst list)

> class TestCase(object):
> 	def __init__(self, pcap = None, sids = []):
> 		self.__Pcap = pcap
> 		self.__lstSid = sids

As you can see in the FAQ entry, the common idiom is to write:

  	def __init__(self, pcap = None, sids = None):
                 if sids is None:
                     sids = []
  		self.Pcap = pcap
  		self._lstSid = sids

Note that I've changed the __names; use __ when you expect a name  
collision with a subclass.
For "implementation only" attributes, use a single underscore; based on  
your appendSid method, lstSid looks like it's used in this way.

> 	def setPcap(self, path):
> 		self.__Pcap = path

This method isn't necesary anymore.

> 	def appendSid(self, sid):
> 	def __str__(self):

Should be changed accordingly.

-- 
Gabriel Genellina




More information about the Python-list mailing list