My CTO is learning Python....

Alex Martelli aleax at aleax.it
Sat Mar 1 07:35:15 EST 2003


Bjorn Pettersen wrote:
   ...
> what I don't understand is why a bound method is special and can be used
> as a staticmethod, while regular functions (def/lambda) cannot? Anyone?

ANY callable except a "regular function" can be "used as a staticmethod"
(and it can ONLY be used that way) -- because looking up an attribute in
a class's dictionary morphs functions into methods (bound or unbound as
appropriate), but it morphs no other types of attribute whatsoever.  Indeed
there's a recipe I put in the online cookbook that uses this to build
static methods for old Python versions very simply (sorry, no URL at
hand, but it shouldn't take you long to find if you're interested!).


This is not a limitation of bound methods -- you can think of it (at
least in the case of newstyle classes, but classic ones work the same
in this respect) as due to the way object.__getattribute__ is coded.
You can, indeed, use such callables as the im_func of a method, but
you must do it explicitly, e.g.:

>>> import new
>>> class X(object): pass
...
>>> class Y(object):
...   def heh(self, other): print '(%s %s)' % (self, other)
...
>>> x=X(); y=Y()
>>> twicebound = new.instancemethod(y.heh, x, X)
>>> twicebound()
(<__main__.Y object at 0x4039e22c> <__main__.X object at 0x4039e26c>)
>>> 
>>> print twicebound.im_self
<__main__.X object at 0x4039e26c>
>>> print twicebound.im_func.im_self
<__main__.Y object at 0x4039e22c>
>>>

Note where the relevant instance objects ARE bound -- one directly to
the method's im_self as usual (the one we pass explicitly when calling
new.instancemethod), the other to the im_self of the im_func, since
the latter is ALSO a bound-method.


Alex





More information about the Python-list mailing list