preventing creation of instance

Troy Melhase troy at gci.net
Wed Jun 18 02:48:59 EDT 2003


Mirko Koenig wrote:
> Is it possible to chech in init if the given name exists in names and
> then destroy itself. So that it will be not possible to create an
> instance of this class, if the given name is existing.

Hi Mirko:

I assume that your test class will need to do real work.  If that's true,
I'd suggest you separate the behaviors of what your class really does and
how its instances are created.  By separating the two, the class gains a
degree of reusability, and the code becomes more clear.  For example:


class actual_test:
    def __init__(self, name):
        self.name = name

def test(name, names={}):
    if name in names:
        return None
    names[name] = newone = actual_test(name)
    return newone


adam = test('Adam')
eve = test('Adam')

assert adam
assert eve is None


Good luck,
troy




More information about the Python-list mailing list