473,805 Members | 2,055 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("hell o")
--------------
....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 1462

"7stud" <bb**********@y ahoo.comwrote in message
news:11******** **************@ p77g2000hsh.goo glegroups.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**********@y ahoo.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...@telcopart ners.comwrote:
"7stud" <bbxx789_0...@y ahoo.comwrote in message

news:11******** **************@ p77g2000hsh.goo glegroups.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).__getattr ibute__(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).__getattr ibute__(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.__getatt ribute__ which
transforms b.x into type(b).__dict_ _['x'].__get__(b, type(b)).
....
For classes, the machinery is in type.__getattri bute__ 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.__getattri bute__(), instead it calls smeth.__get__() directly.
Yet that last sentence from the How-To Guide to Descriptors seems to
say that Test.__getattri bute__() 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**********@y ahoo.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
5934
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
1618
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): super(Metaclass, cls).__init__(cls, name, bases, *args, **kwargs) print 'cls=',cls, cls.__new cls.__new__ = staticmethod(cls.__new) def __new(self,cls,*args):
1
1977
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 means that variabls such as x and y appearing inside class statements in Python essentially behave like static class variables in other languages. On the other hand a variable is specified as an instance variable as self.x and self.y inside a class in...
1
1638
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 guess is that the warning is related to PyChecker not supporting C++ extensions.
5
17269
by: C Gillespie | last post by:
Hi, Does anyone know of any examples on how (& where) to use staticmethods and classmethods? Thanks Colin
2
1888
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
7007
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 understand staticmethod objects don't need to implement __call__ for
0
1313
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 objects returns functions, and classes > always call the __get__ methods of descriptors when those descriptors > are class attributes: Steven D'Aprano wrote: > Why all the indirection to implement something which is, conceptually, > the same as an...
14
2737
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 the two is that classmethod receives the class itself as implicti first argument. From my understanding classmethod are for dealing with class attributes? Can somebody teach me the real use of classmethod & staticmethod?
0
9716
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10609
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10360
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10366
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10105
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9185
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7646
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5542
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4323
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.