Python static method is not always callable

后端 未结 2 846
长情又很酷
长情又很酷 2021-02-08 12:29

While parsing attributes using __dict__, my @staticmethod is not callable.

Python 2.7.5 (default, Aug 29 2016, 10:12:21)         


        
2条回答
  •  孤城傲影
    2021-02-08 12:54

    You can't check if a staticmethod object is callable or not. This was discussed on the tracker in Issue 20309 -- Not all method descriptors are callable and closed as "not a bug".

    In short, there's been no rationale for implementing __call__ for staticmethod objects. The built-in callable has no way to know that the staticmethod object is something that essentially "holds" a callable.

    Though you could implement it (for staticmethods and classmethods), it would be a maintenance burden that, as previously mentioned, has no real motivating use-cases.


    For your case, you can use getattr(C, name) to perform a look-up for the object named name; this is equivalent to performing C.. getattr, after finding the staticmethod object, will invoke its __get__ to get back the callable it's managing. You can then use callable on that.

    A nice primer on descriptors can be found in the docs, take a look at Descriptor HOWTO.

提交回复
热议问题