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
?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With