manually implementing staticmethod()?

Alex Martelli aleax at mac.com
Mon Apr 2 02:56:23 CEST 2007


7stud <bbxx789_05ss at yahoo.com> wrote:
   ...
> I'm using python 2.3.5.
> 
> On Mar 29, 9:34 am, a... at mac.com (Alex Martelli) wrote:
> > Simplest way:
> >
> > class smethod(object):
> >   def __init__(self, f): self.f=f
> >   def __call__(self, *a, **k): return self.f(*a, **k)
> >
> > Alex
> 
> Interesting.  That looks like a functor to me.  Thanks.  I notice that
> __get__() overrides __call__().

Not sure what you mean by "overrides" in this context.  Accessing an
attribute that's a descriptor in the class invokes __get__ (having a
__get__ is the definition of "being a descriptor"); here, we have no
conceivable use for __get__, thus we simply omit it, so that instances
of smethod aren't descriptors and accessing them as attributes does
nothing special whatsoever.  __call__ operates when a call is made, an
operation that is completely separate (and temporally later than) the
"accessing as an attribute" (or whatever other "accessing").

Not sure what you mean by "a functor" (a terminology that's alien to
Python, though I'm sure other languages embrace it whole-heartedly).  If
you mean "a callable that's not a function", why, sure, an instance of
smethod is callable, and it's not a function.  Of course, there are many
other ways of building objects that are callable and aren't functions:

def smethod(f):
    def __new__(cls, *a, **k): return f(*a, **k)
    return type(f.__name__,(),dict(__new__=__new__))

Is this "a functor", too?  I don't really know, nor care -- it's just a
somewhat more intricate way to make callables that aren't functions.


Alex
  



More information about the Python-list mailing list