Good idea to use a class as function with __new__?
glomde
tbrkic at yahoo.com
Mon May 28 08:17:30 EDT 2007
Hi,
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.
So insted of having.
a = Template()
result = a.__TemplateMethod(preifix="foo")
I can write:
result = Template(prefix="foo")
class Template(object):
def __init__(cls, *args, **kwds):
pass
def __new__(cls, *args, **kwds):
obj = super(Template, cls).__new__(cls, *args, **kwds)
return obj.__TemplateMethod(*args, **kwds)
def Customize1(self, prefix="hello", *args, **kwds):
return prefix+"1\n"
def Customize2(self, prefix="hello", *args, **kwds):
return prefix+"2\n"
def __TemplateMethod(self, *args, **kwds):
result = ""
result += self.Customize1(*args, **kwds)
result += self.Customize1(*args, **kwds)
return result
b = Template("foo")
print b
More information about the Python-list
mailing list