[Tutor] use of __new__
A.T.Hofkamp
a.t.hofkamp at tue.nl
Fri Jun 12 14:20:24 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
> (also Normal's supertype has no explicite __new__, but it has an __init__)
Maybe it's just me, but why don't you use a factory function?
def make(args):
if cond(args):
return Special(args)
else:
return Normal(args)
Albert
More information about the Tutor
mailing list