【发布时间】:2016-04-06 15:34:18
【问题描述】:
我有一个函数接受映射,该映射可以是函数的字典,所以我需要区分它们。通常我使用collections 和isinstance/issubclass 中的一些抽象基类来检查参数类型,但函数没有ABC。我知道我可以做到hasattr(mapping, "__call__"),但我想知道是否有更具体的功能。
【问题讨论】:
标签: python python-2.7 oop type-hinting
我有一个函数接受映射,该映射可以是函数的字典,所以我需要区分它们。通常我使用collections 和isinstance/issubclass 中的一些抽象基类来检查参数类型,但函数没有ABC。我知道我可以做到hasattr(mapping, "__call__"),但我想知道是否有更具体的功能。
【问题讨论】:
标签: python python-2.7 oop type-hinting
您可以使用callable(obj),它在 Python 2.7 和 Python 3.2+ 中可用,但在 Python 3.0 或 Python 3.1 中不可用。
你也可以使用types.FunctionType:
isinstance(obj, types.FunctionType)
【讨论】:
types.FunctionType 正是我想要的
您可以为此使用 types 模块,其中定义了 FunctionType:
>>> import types
>>> types.FunctionType
<type 'function'>
>>> def foo(): pass
...
>>> isinstance(foo, types.FunctionType)
True
【讨论】: