Class instantiation question
David C. Fox
davidcfox at post.harvard.edu
Tue Oct 7 16:23:42 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?
As far as I know, the only way to prevent __init__ from creating an
instance is for __init__ to raise an exception which is NOT caught and
handled within __init__. In your example, I think simply doing
class MyClass(self, a, b):
def __init__(self, a, b):
self.one = int(a)
self.two = int(b)
without the try...except block should do it. Then the calling code can
handle the ValueError appropriately.
David
More information about the Python-list
mailing list