manually implementing staticmethod()?
7stud
bbxx789_05ss at yahoo.com
Fri Mar 30 14:48:46 EDT 2007
Hi,
Thanks for the responses.
On Mar 28, 4:01 pm, "Michael Spencer" <m... at telcopartners.com> wrote:
> "7stud" <bbxx789_0... at yahoo.com> wrote in message
>
> news:1175115664.288706.183390 at p77g2000hsh.googlegroups.com...> Hi,
>
> > Can someone show me how to manually implement staticmethod()? Here is
> > my latest attempt:
> > ----------------
>
> Raymond Hettinger can:
>
> http://users.rcn.com/python/download/Descriptor.htm#static-methods-an...
I was using that article to help me. My problem was I was trying to
implement smeth() as a function rather than a class. I hacked around
some more, and I came up with the following before peeking at this
thread for the answer:
class smeth(object):
def __init__(self, func):
self.func = func
def __getattribute__(self, name):
print "smeth -- getattribute"
return super(smeth, self).__getattribute__(name)
def __get__(self, inst, cls=None):
print "smeth get"
return self.func
class Test(object):
def __getattribute__(self, name):
print "Test - gettattribute"
return super(Test, self).__getattribute__(name)
def f():
print "executing f()"
return 10
f = smeth(f)
print Test.f #displays function obj not unbound method obj!
Test.f()
However, my code does not seem to obey this description in the How-To
Guide to Descriptors:
---------
Alternatively, it is more common for a descriptor to be invoked
automatically upon attribute access. For example, obj.d looks up d in
the dictionary of obj. If d defines the method __get__, then
d.__get__(obj) is invoked according to the precedence rules listed
below.***The details of invocation depend on whether obj is an object
or a class***.
...
For objects, the machinery is in object.__getattribute__ which
transforms b.x into type(b).__dict__['x'].__get__(b, type(b)).
...
For classes, the machinery is in type.__getattribute__ which
transforms B.x into B.__dict__['x'].__get__(None, B).
---------
When I examine the output from my code, Test.f does not call
Test.__getattribute__(), instead it calls smeth.__get__() directly.
Yet that last sentence from the How-To Guide to Descriptors seems to
say that Test.__getattribute__() should be called first.
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__().
More information about the Python-list
mailing list