14

Given the following example class:

class Foo:
 def aStaticMethod():
 return "aStaticMethod"
 aVariable = staticmethod(aStaticMethod)
 aTuple = (staticmethod(aStaticMethod),)
 aList = [staticmethod(aStaticMethod)]
print Foo.aVariable()
print Foo.aTuple[0]()
print Foo.aList[0]()

Why would the call to aVariable works properly but with the aTuple and aList it returns the error 'staticmethod' object is not callable?

asked Oct 14, 2010 at 12:14

1 Answer 1

16

It's because a static method is a descriptor. When you attach it to a class and call it with the usual syntax, then python calls its __get__ method which returns a callable object. When you deal with it as a bare descriptor, python never calls its __get__ method and you end up attempting to call the descriptor directly which is not callable.

So if you want to call it, you have to fill in the details for yourself:

>>> Foo.aTuple[0].__get__(None, Foo)()
'aStaticMethod'

Here, None is passed to the instance parameter (the instance upon which the descriptor is being accessed) and Foo is passed to the owner parameter (the class upon which this instance of the descriptor resides). This causes it to return an actual callable function:

>>> Foo.aTuple[0].__get__(None, Foo)
<function aStaticMethod at 0xb776daac>
answered Oct 14, 2010 at 12:27
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.