class factory example needed (long)
Gary Ruben
gazzar at nospam_email.com
Mon Feb 28 07:30:04 EST 2005
Thanks for the very helpful reply Rainer,
I thought I couldn't use setattr because I need the syntactic sugar
sqrt(f) to work, but with your example code Numeric.sqrt(f) does in fact
work correctly. I also need to do a bit more than may be possible with a
simple lambda function, but I should be able to sort it out from here
with the info you provided,
thanks again,
Gary
Rainer Mansfeld wrote:
<snip>
> Hi Gary,
>
> you want your 'class factory' to change the methods of Numeric, so that
> they accept foo objects and return foo objects?
> I've not the slightest idea how to achieve that.
>
> 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
>
More information about the Python-list
mailing list