making a class return None from __init__
Chad Netzer
cnetzer at mail.arc.nasa.gov
Fri Oct 4 17:16:52 EDT 2002
On Friday 04 October 2002 13:46, Max M wrote:
> Rajarshi Guha wrote:
> > (where v will fail) I always get <__main__.Graph instance at
> > 0xXXXXXX> Is there any way to make the constructor return a None
> > object?
>
> def noner():
> return
ie. Create a factory function that returns the initialized class when
everything goes well, or None upon failure:
class MyClass:
def __init__( self, arg1, arg2, arg3 ):
return
def MyClassFactory( arg1, arg2, arg3 ):
if valid_args( arg1, arg2, arg3 )
return MyClass( arg1, arg2, arg3 )
else:
return None
Note - this is arguably bad style, UNLESS it is clear that you are
invoking a factory rather than a class constructor. Typically, you use
a factory to have flexibility in choosing which class is actually
instantiated, NOT because you need to test error conditions.
Better to use exceptions in the __init__, and abort the class
initialization if you cannot use the class. Returning either a class
or None, just doesn't feel right, especially if the user is assuming
only one specific class to be created.
--
Chad Netzer
cnetzer at mail.arc.nasa.gov
More information about the Python-list
mailing list