Question: How to only create new object instances?

Joal Heagney s713221 at student.gu.edu.au
Sat Oct 27 09:17:56 EDT 2001


Michael McGovern wrote:
> 
> I am trying to create new cells only when they don't exist in a given library
> of cells.  In the case where they already exist in the supplied library, I
> would like the "new" cell to refer to the exisiting cell in the library.
 
> >>> from Cell import *
> >>> lib1 = Library(name='lib1')
> >>> i1 = Cell(cellName='A1',library=lib1)
> >>> i2 = Cell(cellName='A1',library=lib1)
> cell already exists
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: __init__() should return None
> >>>

The problem is exactly what the traceback reports. __init__() functions
should return None, but in your definition, you're trying to return
library.cellList[cellName].

> How can I accomplish this?

Unless others can come up with more valid methods to achieve this, maybe
you want to give up on Cell as a class, and turn it into a helper
function instead?

def Cell(self, cellName, library=None):
	if cellName in library.cellList.keys():
		print "cell already exists"
		return library.cellList[cellName]
	etc.

Or, looking at you're code, it may well be able to fiddle this into a
__getitem__ method of you're library class and subsume the cell class
entirely?

>>> class ListLibrary:
	# You're checking that entries aren't already in there anycase.
	# There's no benefit for using a dictionary in this case, unless
	# you plan to access the list/dictionary from outside the class, which
is
	# bad practice anyway.
	libList = []
	def __init__(self):
		# probably can do away with this first bit, as self, by design, is
meant to be unique.
		if self not in self.libList:
			self.libList.append(self)
			self.cellList = []
	def add_cell(self,cell):
		if cell not in self.cellList:
			self.cellList.append(cell)
		else:
			print cell, " already exists in ", self, "\n"
	def __getitem__(self,cell):
		# add_cell already does the error-checking, we'll trust it
		# and just return the cell value.
		self.add_cell(cell)
		return cell
	def __repr__(self):
		return "%s" % self.cellList

	
>>> lib1 = ListLibrary()
>>> lib1.add_cell('hello')
>>> lib1
['hello']
>>> lib1['goodbye']
'goodbye'
>>> lib1
['hello', 'goodbye']
>>> lib1['goodbye']
goodbye  already exists in  ['hello', 'goodbye'] 

'goodbye'
>>>

It's a bit of a beginner's hack I must admit, expecting a __getitem__ to
dynamically alter the object that it's retreiving data from. I expect to
get flamed down by the community post-haste :).
-- 
      Joal Heagney is: _____           _____
   /\ _     __   __ _    |     | _  ___  |
  /__\|\  ||   ||__ |\  || |___|/_\|___] |
 /    \ \_||__ ||___| \_|! |   |   \   \ !



More information about the Python-list mailing list