preventing creation of instance

Alexander Schmolck a.schmolck at gmx.net
Wed Jun 18 02:33:17 CEST 2003


Peter Hansen <peter at engcorp.com> writes:

> Mirko Koenig wrote:
> > 
> > I have a class with a 'static' list of names to control if every instance
> > of the class has a different name.
> > 
> > class test:
> >         names = []
> >         def __init__( self, name ):
> >                 ...
> > 
> > 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.
> > 
> > adam = test( "adam" ) # should work
> > eve = test ( "adam" ) #should then not work. eve should be None.
> 
> I believe raising any exception in __init__ is the way to prevent
> the creation of the object.  I don't think you can do this with
> a technique that returns None, unless you are actually calling
> a factory function which internally attempts to create the object
> and catches the exception thrown, returning None if it happens.


>>> class Test(object):
...    def __new__(cls): return None
...
>>> Test()
>>> 

see http://www.python.org/2.2/descrintro.html#__new__

'as




More information about the Python-list mailing list