views:

31

answers:

1

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?

+2  A: 

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>
aaronasterling