473,503 Members | 2,238 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

manually implementing staticmethod()?

Hi,

Can someone show me how to manually implement staticmethod()? Here is
my latest attempt:
----------------
def smethod(func):

def newFunc():
pass

def newGet():
print "new get"

newFunc.__get__ = newGet

return newFunc

class Test(object):

def show(msg):
print msg
show = smethod(show)
Test.show("hello")
--------------
....but I keep getting the error:

TypeError: unbound method newFunc() must be called with Test instance
as first argument (got str instance instead)

I think I need to intercept the function's __get__() method in order
to block creation of the method object, which requires that the
unbound method call provide an instance.

Mar 28 '07 #1
4 1444

"7stud" <bb**********@yahoo.comwrote in message
news:11**********************@p77g2000hsh.googlegr oups.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...-class-methods


Mar 28 '07 #2
7stud <bb**********@yahoo.comwrote:
Hi,

Can someone show me how to manually implement staticmethod()? Here is
Simplest way:

class smethod(object):
def __init__(self, f): self.f=f
def __call__(self, *a, **k): return self.f(*a, **k)
Alex
Mar 29 '07 #3
Hi,

Thanks for the responses.
On Mar 28, 4:01 pm, "Michael Spencer" <m...@telcopartners.comwrote:
"7stud" <bbxx789_0...@yahoo.comwrote in message

news:11**********************@p77g2000hsh.googlegr oups.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...tic-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...@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__().

Mar 30 '07 #4
7stud <bb**********@yahoo.comwrote:
...
I'm using python 2.3.5.

On Mar 29, 9:34 am, a...@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

Apr 2 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
5910
by: Michal Vitecek | last post by:
hello everyone, today i've come upon a strange exception, consider the following file test.py: --- beginning of test.py --- class A(object): def method1(parA): print "in A.method1()"
0
1592
by: Robin Becker | last post by:
A colleague wanted to initialize his class __new__ and tried code resembling this #######################1 class Metaclass (type): def __init__(cls, name, bases, *args, **kwargs):...
1
1962
by: Neil Zanella | last post by:
Hello, Coming from C++ and Java, one of the surprising things about Python is that not only class instances (AKA instance objects) but also classes themselves are objects in Python. This...
1
1617
by: Olaf Meding | last post by:
What does the below PyChecker warning mean? More importantly, is there a way to suppress it? PyChecker warning: ..\src\phaseid\integration.py:21: self is argument in staticmethod My best...
5
17252
by: C Gillespie | last post by:
Hi, Does anyone know of any examples on how (& where) to use staticmethods and classmethods? Thanks Colin
2
1870
by: Neal Becker | last post by:
How can I write code to take advantage of new decorator syntax, while allowing backward compatibility? I almost want a preprocessor. #if PYTHON_VERSION >= 2.4 @staticmethod ....
10
6976
by: Nicolas Fleury | last post by:
Hi everyone, I was wondering if it would make sense to make staticmethod objects callable, so that the following code would work: class A: @staticmethod def foo(): pass bar = foo() I...
0
1293
by: Steven Bethard | last post by:
Steven Bethard wrote: > (For anyone else out there reading who doesn't already know this, > Steven D'Aprano's comments are easily explained by noting that the > __get__ method of staticmethod...
14
2704
by: james_027 | last post by:
hi, python's staticmethod is the equivalent of java staticmethod right? with classmethod, I can call the method without the need for creating an instance right? since the difference between...
0
7291
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7357
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7468
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5598
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5023
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4690
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3180
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
1
748
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
402
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.