Re: class factory example needed (long)

From: Gary Ruben (gazzar_at_nospam_email.com)
Date: 03/01/05


Date: Tue, 01 Mar 2005 09:56:23 GMT

OK, I've managed to get this to work with Rainer's method, but I
realised it is not the best way to do it, since the methods are being
added by the constructor, i.e. they are instance methods. This means
that every time a foo object is created, a whole lot of code is being
run. It would be better to do the same thing with class 'static'
methods, if this is possible, so that the methods are created just once.
Is this possible?
Gary

Rainer Mansfeld wrote:
<snip>
> If OTOH you want your foo class to have sqrt, arccos, etc. methods
> without defining them explicitly, I think you're looking for something
> like:
>
> . import Numeric
> .
> . class Foo(object):
> . def __init__(self, value):
> . self.value = float(value)
> . for u in ['sqrt', 'cos', 'tan']:
> . setattr(self, u, lambda uf=getattr(Numeric, u):
> . uf(self.value + 42.0))
>
> >>> f = Foo(7)
> >>> f.sqrt()
> 7.0
>
> HTH
> Rainer