Re: Why require __init__ to return None?
Guido.van.Rossum@cwi.nl
Fri, 27 May 1994 17:27:30 +0200
> I am trying to write a generator that is initialized with a list
> and then returns each element sequentially.
>
> The easiest way to do this seemed to be to write a class, like so:
>
> class Iterator:
> def __init__(self, list):
> self.list=list
> self.pos=-1
> return self.generator
> def generator(self):
> self.pos = self.pos + 1
> return self.list[self.pos]
>
> Thus, when the user called Iterator with a list:
>
> Iterator([1,2,3,4,5])
>
> This would then initialize the instance with the list, and return
> an instance method (not the instance itself). This method (generator)
> would then return 1, 2, etc.
>
> >>> x = Iterator([1,2,3,4,5])
> >>> x()
> 1
> >>> x()
> 2
>
> Unfortunately, Python requires that __init__ return None.
>
> What I propose is that the user should be able to override the default
> return value of __init__, by explicitly returning a value other than
> None.
>
> I know that I can just write another function to return the generator,
> but then my creation syntax becomes:
>
> >>> x = Iterator().make([1,2,3,4,5])
>
> which is not as pretty.
A solution without changing the interpreter is to rename your class to
_Iterator and have a (global) function as follows:
def Iterator(list):
return _Iterator(list).generator
This can be called as in your first example.
Your proposal violates a property that I quite like: if classname(...)
returns, it returns an instance of class 'classname'. If you don't
want that, it shouldn't be a class. Note that C++ constructors can't
return a value either...
--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
URL: <http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>