[Tutor] use of __new__

Kent Johnson kent37 at tds.net
Fri Jun 12 16:03:08 CEST 2009


On Fri, Jun 12, 2009 at 9:48 AM, spir<denis.spir at free.fr> wrote:
> Right, thank you. I continued my trials and ended with seemingly working code, close to yours.
>
>                # case pattern is Klass: yield String instead
>                if isinstance(pattern,Klass):
>                        self = String(pattern, numMin,numMax, expression,name)
> #~                      self.__init__(pattern, numMin,numMax, expression,name)
>                        return self
>                # else a Repetition
>                self = Pattern.__new__(cls,pattern, numMin,numMax, expression,name)
>                return self
>
> I have more questions:

> 2. For the special case, as you can see the __init__ line is commented out and it works anyway. While the docs positively assert that __init__ *won't* be called if an object of a different type is returned, it is anyway.

When you call String(...) you invoke String.__new__() and
String.__init__(), so String.__init__() is not called by the normal
mechanism.

If your special case returned for example a cached instance of
String(), then String.__init__() would not be called as part of the
invocation of your __new__().

Kent


More information about the Tutor mailing list