function factory question: embed current values of object attributes

Terry Reedy tjreedy at udel.edu
Fri Feb 20 16:26:55 EST 2009


Alan Isaac wrote:
> I have a class `X` where many parameters are set
> at instance initialization.  The parameter values
> of an instance `x` generally remain unchanged,

'Parameters' are the function local names in the header that get bound 
to argument objects when the function is called.  What you are 
describing are 'attributes'.

> 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)?

In the terms stated, no.

> 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).

You are now describing a function closure.  Here is an example that 
might help.

def f_maker(a1, a2):
   def _(b): return a1*b + a2
   return _

class C:
   def __init__(self, attr1, attr2):
     self.attr1 = attr1
     self.attr2 = attr2
     self.f = f_maker(attr1, attr2)

c = C(2,3)
print(*(c.f(i) for i in range(5)))

# 3 5 7 9 11

Having f use both initial and 'current' attribute values would be a bit 
trickier ;-)

Terry Jan Reedy




More information about the Python-list mailing list