preventing creation of instance
Peter Hansen
peter at engcorp.com
Tue Jun 17 19:13:35 EDT 2003
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.
-Peter
More information about the Python-list
mailing list