Twice instanciation
Michele Simionato
mis6 at pitt.edu
Fri Jun 13 08:03:26 EDT 2003
Salvatore <artyprog at wanadoo.fr> wrote in message news:<bcakmg$jv7$1 at news-reader14.wanadoo.fr>...
> 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:
alreadyinstantiated=False
def __init__(self,init=0):
if self.__class__.alreadyinstantiated:
raise DoubleInstantiationError()
self.value = init
self.__class__.alreadyinstantiated=True
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.
HTH,
Michele
Michele
More information about the Python-list
mailing list