How to use a class property to store function variables?

alex23 wuwei23 at
Tue Apr 27 22:20:35 EDT 2010

GZ <zyzhu2... at> wrote:
> I do not think it will help me. I am not trying to define a function
> fn() in the class, but rather I want to make it a "function reference"
> so that I can initialize it any way I like later.

It always helps to try an idea out before dismissing it out of hand.
Experimentation in the interpreter is cheap and easy.

>>> class A(object):
...   fn = staticmethod(lambda x: x*x)
>>> A.fn(10)
>>> A.fn = staticmethod(lambda x: x**x)
>>> A.fn(3)
>>> def third(x): return x/3
>>> A.fn = staticmethod(third)
>>> A.fn(9)

However, I'm assuming you're wanting to do something like this:

>>> class B(object):
...   def act(self):
...     print self.fn()

That is, providing a hook in .act() that you can redefine on demand.
If so, note that you only need to decorate functions as staticmethods
if you're assigning them to the class. If you intend on overriding on
_instances_, you don't:

>>> B.fn = staticmethod(lambda: 'one') # assign on class
>>> b = B() # instantiate
>>> b.act() # act on instance
>>> B.fn = staticmethod(lambda: 'two') # assign on class
>>> b.act() # existing instance calls new version on class
>>> b.fn = staticmethod(lambda: 'three') # assign on instance
>>> b.act()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in act
TypeError: 'staticmethod' object is not callable
>>> b.fn = lambda: 'three' # look Ma, no staticmethod!
>>> b.act()

Incidentally, this is known as the Strategy pattern, and you can see a
simple example of it in Python here:

Hope this helps.

More information about the Python-list mailing list