Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
648 views
in Technique[技术] by (71.8m points)

python - 'staticmethod' object is not callable

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 run this I keep getting the error:

TypeError: 'staticmethod' object is not callable

how to resolve it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are storing unbound staticmethod objects in a dictionary. Such objects (as well as classmethod objects, functions and property objects) are only bound through the descriptor protocol, by accessing the name as an attribute on the class or an instance. Directly accessing the staticmethod objects in the class body is not an attribute access.

Either create the dictionary after creating the class (so you access them as attributes), or bind explicitly, or extract the original function before storing them in the dictionary.

Note that 'binding' for staticmethod objects merely means that the context is merely ignored; a bound staticmethod returns the underlying function unchanged.

So your options are to unindent the dictionary and trigger the descriptor protocol by using attributes:

class A(object):
    @staticmethod
    def open():
        return 123
    @staticmethod
    def proccess():
        return 456

A.switch = {
    1: A.open,
    2: A.proccess,   
}

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

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 underlying function directly with 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 a class object in the first place. Put the functions in a module. That way you don't have to use staticmethod decorators in the first place and don't have to unwrap them again.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...