找出Python对象是否可调用

时间:2015-10-08 00:42:30

标签: python-3.x

我想知道某个对象是否可以调用。

我知道type()会返回<class 'method'>。但我不知道如何检查(例如isinstance())。

2 个答案:

答案 0 :(得分:3)

如果您必须使用 isinstance,您可以检查 Callable:

from typing import Callable
obj = lambda x: x + 1
isinstance(obj, Callable)
>>> True
obj = 42
isinstance(obj, Callable)
>>> False

答案 1 :(得分:2)

使用内置callable()

>>> callable(open)
True
>>> print(callable.__doc__)
callable(object) -> bool

Return whether the object is callable (i.e., some kind of function).
Note that classes are callable, as are instances with a __call__() method.

这是一项很好的投资,目的是掌握至少90%的内置函数:https://docs.python.org/3/library/functions.html