How to use a class property to store function variables?

GZ zyzhu2000 at gmail.com
Wed Apr 28 07:55:41 CEST 2010


On Apr 27, 9:20 pm, alex23 <wuwe... at gmail.com> wrote:
> GZ <zyzhu2... at gmail.com> 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)
> 100
> >>> A.fn = staticmethod(lambda x: x**x)
> >>> A.fn(3)
> 27
> >>> def third(x): return x/3
> ...
> >>> A.fn = staticmethod(third)
> >>> A.fn(9)
>
> 3
>
> 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
> one
> >>> B.fn = staticmethod(lambda: 'two') # assign on class
> >>> b.act() # existing instance calls new version on class
> two
> >>> 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()
>
> three
>
> Incidentally, this is known as the Strategy pattern, and you can see a
> simple example of it in Python here:http://en.wikipedia.org/wiki/Strategy_pattern#Python
>
> Hope this helps.

Ah, this totally works. The key is to use the staticmethod function.
Thanks a lot.



More information about the Python-list mailing list