How to use a class property to store function variables?
zyzhu2000 at gmail.com
Wed Apr 28 02:02:02 EDT 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)
> >>> 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:http://en.wikipedia.org/wiki/Strategy_pattern#Python
> Hope this helps.
Another question: I am not sure how staticmethod works internally. And
the python doc does not seem to say. What does it do?
More information about the Python-list