Twice instanciation

Michele Simionato mis6 at
Fri Jun 13 14:03:26 CEST 2003

Salvatore <artyprog at> wrote in message news:<bcakmg$jv7$1 at>...
> Hello,
> Is it possible to avoid twice instanciation
> of the same variable ?
> class Global:
>     def __init__(self,init=0):
>        self.value = init
> g = Global() #instanciating one time ok
> g = Global() #instanciating two times would raise an exception
> Regards
> Salvatore

You can do this:

class DoubleInstantiationError(Exception): pass

class Global:
    def __init__(self,init=0):
        if self.__class__.alreadyinstantiated:
            raise DoubleInstantiationError()
        self.value = init

g = Global() #instanciating one time ok
print g
g = Global() #instanciating two times would raise an exception

Notice that you would have an exception even using a different name
for 'g' the second time. You can alway subclass Global, anyway, if
you need another variable.



More information about the Python-list mailing list