确定 Python 对象是否可调用

buh*_*htz 5 python-3.x

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

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

Sha*_*lgi 24

如果您必须使用isinstance,您可以检查Callable(Python \xe2\x89\xa5 3.5):

\n
from typing import Callable\nobj = lambda x: x + 1\nisinstance(obj, Callable)\n>>> True\nobj = 42\nisinstance(obj, Callable)\n>>> False\n
Run Code Online (Sandbox Code Playgroud)\n


Eli*_*les 10

使用内置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.
Run Code Online (Sandbox Code Playgroud)

努力掌握此处列出的至少 90% 的内置函数是一项巨大的投资:https : //docs.python.org/3/library/functions.html