Question: How to only create new object instances?
s713221 at student.gu.edu.au
Sat Oct 27 15:17:56 CEST 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
> 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
def Cell(self, cellName, library=None):
if cellName in library.cellList.keys():
print "cell already exists"
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
>>> 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
# bad practice anyway.
libList = 
# probably can do away with this first bit, as self, by design, is
meant to be unique.
if self not in self.libList:
self.cellList = 
if cell not in self.cellList:
print cell, " already exists in ", self, "\n"
# add_cell already does the error-checking, we'll trust it
# and just return the cell value.
return "%s" % self.cellList
>>> lib1 = ListLibrary()
goodbye already exists in ['hello', '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