[Tutor] use of __new__

Lie Ryan lie.1296 at gmail.com
Fri Jun 12 14:37:17 CEST 2009


spir wrote:
> Hello,
> 
> I have (again) some issue using __new__.
> What I need is basically to catch an object creation and yield an object of an alternate type, when a condition is met.
> 
> Basically, the outline looks like:
> 
> class Normal(object):
>     def __new__(cls, arg):
>         if cond(arg):
>             # <yield instance of Special>
>             # expression is simply: Special(arg)
>             # must be __init__ialised !
>         
>         # Conceptually, nothing to change:
>         # <yield instance of Normal>
>         # must be __init__ialised !
> 
> But I got issues in both cases:
> * cannot find how to get Special objects initialised
> * cannot find how to return Normal object

roughly like this:

>>> class Special(object):
...     def __init__(self, arg):
...         self.arg = arg
...
>>> class Normal(object):
...     def __new__(cls, arg):
...         if arg:
...             return Special(arg)
...         else:
...             ret = super(Normal, cls).__new__(cls)
...             ret.__init__(arg)
...             return ret
...     def __init__(self, arg):
...         self.arg = arg
...
>>> a = Normal(True)
>>> b = Normal(False)
>>> a.arg
True
>>> b.arg
False
>>>

generally though, avoid using __new__


> (also Normal's supertype has no explicite __new__, but it has an __init__)

Haven't tested yet, but that should be no problem as python will use the
supertype's supertype's __new__ and at the end of the method resolution
order is object.__new__()



More information about the Tutor mailing list