Class instantiation question

Carl Banks imbosol at aerojockey.invalid
Tue Oct 7 15:16:58 EDT 2003


Todd Johnson wrote:
> Ok, say I have a class MyClass and an __init__(self,
> a, b)  Say that a and b are required to be integers
> for example. So my init looks like:
> 
> __init__(self, a, b):
>    try:
>        self.one = int(a)
>        self.two = int(b)
>    except ValueError:
>        #nice error message here
>        return None
> 
> I have even tried a similar example with if-else
> instead of try-except, but no matter what if I call
> 
> thisInstance = MyClass(3, "somestring")
> 
> it will set self.one to 3 and self.two will be
> uninitialised. The behavior I am hoping for, is that
> thisInstance is not created instead(or is None). How
> do I get the behavior I am looking for?


1. I highly recommend you rethink your programming.  Are you planning
   to handle the error in the function that called the MyClass
   contructor?  In other words, are you doing something like this:

       def some_function(a,b):
           thisInstance = MyClass(a,b)
           if thisInstance is None:
               handle_error()
           else:
               do_something_useful(thisInstance)

   If so, you are not taking full advantage of the exception handling
   mechanism.  The best way to do it is like this:

       def some_function(a,b):
           try:
               thisInstance = MyClass(a,b)
           except ValueError:
               handler_error()
           else:
               do_something_useful(thisInstance)

   As always, a larger code snippet can help us help you with that, if
   you wish.


2. If you're sure the behavior you want is to return None if a or b is
   not an integer, then I recommned you use a factory function:

       def my_class_maker(a,b):
           try:
               return MyClass(a,b)
           except ValueError:
               return None


-- 
CARL BANKS                   http://www.aerojockey.com/software

As the newest Lady Turnpot descended into the kitchen wrapped only in
her celery-green dressing gown, her creamy bosom rising and falling
like a temperamental souffle, her tart mouth pursed in distaste, the
sous-chef whispered to the scullery boy, "I don't know what to make of
her." 
          --Laurel Fortuner, Montendre, France 
            1992 Bulwer-Lytton Fiction Contest Winner




More information about the Python-list mailing list