Can __init__ not return an object?

Kay Schluehr kay.schluehr at gmx.net
Mon Apr 23 12:30:10 EDT 2007


On Apr 22, 4:36 am, "Steven W. Orr" <ste... at syslang.net> wrote:
> When I go to create an object I want to be able to decide whether the
> object is valid or not in __init__, and if not, I want the constructor to
> return something other than an object, (like maybe None). I seem to be
> having problems. At the end of __init__ I say (something like)
>
>         if self.something < minvalue:
>             del self
>             return None
>
> and it doesn't work. I first tried just the return None, then I got crafty
> and tried the del self. Is what I'm trying to do possible in the
> constructor or do I have to check after I return? Or would raising an
> exception in the constructor be appropriate?

You can raise an exception of course but it would just create a side
effect. Another way to achieve what you request for is manipulating
the class creation mechanism.

class A(object):
    def __new__(cls, x):
        if x == 0:
            return None
        obj = object.__new__(cls)
        obj.__init__(x)
        return obj

class B(A):
    def __init__(self, x):
        self.x = x

The condition can always be checked within the static __new__ method.

Kay




More information about the Python-list mailing list