Class instantiation question
Matt Brubeck
mbrubeck at cs.hmc.edu
Tue Oct 7 20:08:52 EDT 2003
Todd Johnson <overdrive_ss at yahoo.com> 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?
Here's one option:
>>> class C:
... def __init__(self, a):
... self.a = int(a)
...
>>> c = C("hello")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in __init__
ValueError: invalid literal for int(): hello
This also allows the following:
>>> try: c = C("hello")
... except ValueError: c = None
...
>>> print c
None
If you really want initialization to return None instead of raising an
exception, you can override the __new__ method of a new-style class:
>>> class C(object):
... def __new__(cls, a):
... try: a = int(a)
... except ValueError: return None
... return object.__new__(cls, a)
... def __init__(self, a):
... self.a = a
...
>>> c = C(1)
>>> c.a
1
>>> c = C("hello")
>>> print c
None
More information about the Python-list
mailing list