[Tutor] Why error if method __init__ does not return none

Drew Perttula drewp@bigasterisk.com
Sat Mar 22 18:36:42 2003


> At 10:17 PM 3/22/2003 +0100, Gerrit Holl wrote:
> 
> >This raises an interesting question. Shouldn't it say: __init__ should
> >return self...? Because _that_ is what it really does...
> 
> Interesting idea. Then it could even return something different, in which 
> case calling the class would be like calling a function.
> 

What makes you think __init__ "really" returns self? I'm happy it doesn't, in fact,
since the instance is in no way a "product of" __init__. The instance is generated
elsewhere, and it's an input to the initializer function. It *could* be an output,
but that would be purely for convenience, and I propose that convenience doesn't
even help anyone.

Another note:

class MyClass(Parent1,Parent2):
  def __init__(self,*args):
     Parent1.__init__(self,*someargs)
     Parent2.__init__(self,*otherargs)

The latter two calls didn't return anything of interest. They might have
returned their self arguments, and I suppose we wouldn't care. (They
don't, though.)


However, we all know that when I say "m=MyClass()", MyClass returns a
new MyClass instance. It is indeed remarkably like calling a function
that returns the new instance, although it's not like simply calling
the __init__ function. The deliberate function call syntax means that
if you wanted to, you could actually swap in a function, and probably
no one would notice.

-----first version---------------

class LimitedResource:
  pass

lots_of_code_that_uses(LimitedResource)

------next version----------------

class LimitedResource:
  pass

_LimitedResource=LimitedResource # another name for the class- the class's own name is unharmed

def LimitedResource(*args):
  if resources_left():
    return _LimitedResource()
  else:
    raise "no more resource!"

exactly_the_same_code_that_uses(LimitedResource)

-----------------------------------

Advanced Python users will remark that the __new__ class method can now
be used for these purposes. 

-Drew