class factory example needed (long)

Gary Ruben gazzar at nospam_email.com
Tue Mar 1 04:56:23 EST 2005


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



More information about the Python-list mailing list