function factory question: embed current values of object attributes

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Feb 20 23:52:05 EST 2009


En Fri, 20 Feb 2009 16:49:21 -0200, Alan Isaac <aisaac at american.edu>  
escribió:

> I have a class `X` where many parameters are set
> at instance initialization.  The parameter values
> of an instance `x` generally remain unchanged,
> but is there way to communicate to a method that
> it depends only on the initial values of these parameters
> (and does not need to worry about any changes)?
>
> The behavior of method `m` depends on these parameter values.
> It turns out `m` gets called a lot, which means
> that the pameter values are accessed over and over
> (self.p0, self.p1, etc).  I would like to
> manufacture a function equivalent to the method
> that simply uses fixed values (the values at the
> time it is manufactured).  I do not care if this
> function is attached to `x` or not.

Not automatically; but you could refactor the method to call an external  
function with arguments:

class X(...):
   ...
   def foo(self):
     c = self.a + self.b
     return c

Rewrite the method as:

   def foo(self):
     return _foo(self.a, self.b)

and define _foo outside the class:

def _foo(a, b):
   c = a + b
   return c

If you want a "frozen" function (that is, a function already set-up with  
the parameters taken from the current values of x.a, x.b) use  
functools.partial:

x = X()
frozen_foo = functools.partial(_foo, a=x.a, b=x.b)
frozen_foo() # equivalent to x.foo() at the time it was defined

But if you call this in a loop, perhaps it's enough to assign x.a, x.b to  
local variables and call _foo with those arguments.

-- 
Gabriel Genellina




More information about the Python-list mailing list