Good idea to use a class as function with __new__?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon May 28 12:23:39 EDT 2007


En Mon, 28 May 2007 09:17:30 -0300, glomde <tbrkic at yahoo.com> escribió:

> I am implementing som code generation and want to to use some variant
> of the template method pattern.
>
> What I came up with is to have a class with the common part
> in a method and the subclasses can then override the Customize methods
> to do their own special part.
>
> Now to the question I use the __new__ to return the result instead
> of the instance. So that the class is used as an function.

It works, and I don't see any big problems, but I don't *like* that.
I'd use __call__ instead; that is, write __new__ and __init__ normally -if  
you need them at all- and move the magic to __call__:

     def __call__(self, *args, **kwds):
        return self.__TemplateMethod(*args, **kwds)

x = Template()(prefix="foo")
or perhaps:
x = Template(prefix="foo")()

I think the extra () improves readability - it's clear that x comes from a  
function call, it's not a Template instance as one would expect from your  
original code.
And depending on the application, you could keep the instances and call  
them with different arguments - with the original code you always create a  
new instance just to discard it immediately.

-- 
Gabriel Genellina




More information about the Python-list mailing list