preventing creation of instance
Alexander Schmolck
a.schmolck at gmx.net
Wed Jun 18 11:19:37 EDT 2003
Peter Hansen <peter at engcorp.com> writes:
> Alexander Schmolck wrote:
> >
> > Peter Hansen <peter at engcorp.com> writes:
> > > 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__
>
> D'oh! I really ought to find a reason to learn about the
> "__new__-fangled" methods in the latest Python releases...
>
> I just can't seem to find a reason to use them though (yet).
I agree with your advice of raising an exception to prevent object creation
(so this example doesn't merrit __new__, I think). However, if you want to
return e.g. always the same object (or cached objects) or (a bit more
perversely) an object of another type upon instance creation __new__ comes in
handy. I think an important advantage of __new__ over factory functions is
that this special cration mechanism is is transparently and automatically
available via instances. Thus e.g.
def doSomething(self):
newObject = self.__class__()
return newObject
or
newThing = type(thing)()
will do the right thing (e.g. return cached instances), without needing to
know about a factory function.
'as
More information about the Python-list
mailing list