Returning 'None' on Instantiation ?

Mark Hammond MarkH at ActiveState.com
Fri Jun 1 09:41:45 EDT 2001


Dave Haynes wrote:

> Is there a way to optionally return 'None' on instantiation? 


Not literally.

> I'm thinking of something like the following:
> 
> class myClass:
>     def __init__(self, param):
> 
>         if <check param>:
>             <initialise data members>
>         else:
>             <make self a 'None object'>


The "best" way IMO is to raise an exception here:
           if <check param:
               ...
           else:
              raise ValueError, "param a is wrong"

Then your caller has access to the specific problem:

try:
   inst = myClass(foo)
except ValueError, why:
   print "Error making instance:", why
   inst = None

Mark.




More information about the Python-list mailing list