How to use a class property to store function variables?

Chris Rebert clp2 at rebertia.com
Wed Apr 28 02:20:15 EDT 2010


On Tue, Apr 27, 2010 at 11:02 PM, GZ <zyzhu2000 at gmail.com> wrote:
> 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.
>
> Another question: I am not sure how staticmethod works internally. And
> the python doc does not seem to say. What does it do?

It involves the relatively arcane magic of "descriptors".
See http://docs.python.org/reference/datamodel.html#implementing-descriptors
or for a more complete but advanced explanation, the "Static methods
and class methods" section of
http://www.python.org/download/releases/2.2.3/descrintro/

Understanding exactly how staticmethod() and friends work is not too
essential in practice though.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list