【问题标题】:Python 2: function abstract typePython 2:函数抽象类型
【发布时间】:2016-04-06 15:34:18
【问题描述】:

我有一个函数接受映射,该映射可以是函数的字典,所以我需要区分它们。通常我使用collectionsisinstance/issubclass 中的一些抽象基类来检查参数类型,但函数没有ABC。我知道我可以做到hasattr(mapping, "__call__"),但我想知道是否有更具体的功能。

【问题讨论】:

    标签: python python-2.7 oop type-hinting


    【解决方案1】:

    您可以使用callable(obj),它在 Python 2.7 和 Python 3.2+ 中可用,但在 Python 3.0 或 Python 3.1 中不可用。

    你也可以使用types.FunctionType:

    isinstance(obj, types.FunctionType)
    

    【讨论】:

    • types.FunctionType 正是我想要的
    【解决方案2】:

    您可以为此使用 types 模块,其中定义了 FunctionType

    >>> import types
    >>> types.FunctionType
    <type 'function'>
    >>> def foo(): pass
    ... 
    >>> isinstance(foo, types.FunctionType)
    True
    

    【讨论】:

      猜你喜欢
      • 2012-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 1970-01-01
      • 2016-08-21
      • 1970-01-01
      相关资源
      最近更新 更多