Staticmethod object not called

I have this code:

class A(object): @staticmethod def open(): return 123 @staticmethod def proccess(): return 456 switch = { 1: open, 2: proccess, } obj = A.switch[1]() 

When I start, I get an error message:

 TypeError: 'staticmethod' object is not callable 

how to solve it?

+34
python
source share
1 answer

You save unrelated staticmethod objects in a dictionary. Such objects (as well as classmethod objects, functions and property objects) are connected only through the descriptor protocol , referring to the name as an attribute of a class or instance. Direct access to staticmethod objects in a class cube is not attribute access.

Either create a dictionary after creating the class (so that you can access them as attributes), either directly bind or retrieve the original function before storing them in the dictionary.

Note that binding for staticmethod objects simply means that the context is simply ignored; the associated staticmethod returns the underlying function unchanged.

So your options are to cancel the dictionary and start the descriptor protocol using the attributes:

 class A(object): @staticmethod def open(): return 123 @staticmethod def proccess(): return 456 A.switch = { 1: A.open, 2: A.proccess, } 

or explicitly bind, passing in a dummy context (which will still be ignored):

 class A(object): @staticmethod def open(): return 123 @staticmethod def proccess(): return 456 switch = { 1: open.__get__(object), 2: proccess.__get__(object), } 

or access the base function directly using the __func__ attribute:

 class A(object): @staticmethod def open(): return 123 @staticmethod def proccess(): return 456 switch = { 1: open.__func__, 2: proccess.__func__, } 

However, if all you are trying to do is provide a namespace for a bunch of functions, then you should not use the class object in the first place. Put the functions in the module. Thus, you do not need to use staticmethod decorators in the first place and you do not need to deploy them again.

+45
source share

All Articles