【问题标题】:Check whether a callable is a class or a function [duplicate]检查可调用对象是类还是函数[重复]
【发布时间】:2019-03-28 18:07:59
【问题描述】:

在python中,类和函数都是可调用的,但就我而言,我只想调用函数。

示例代码:

class AClass:
    pass

def a_func():
    pass
type(AClass)

# Output: 
<class 'type'>

type(a_func)

# Output:
<class 'function'>

所以,我的实际问题是我如何写一个 if 说这样的话:

if type(something) == <a function type>:
    # call the function 

我试过这样做:

if isinstance(AClass, type):
    # passes through

if isinstance(a_func, type):
    # passes through too

所以,检查输入 isinstance,我无法让它工作。

我正在与 type 和 isinstance() 进行比较,任何其他解决方法也将不胜感激。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:
    from types import FunctionType
    
    def a():
        pass
    
    isinstance(a, FunctionType)
    >>> True
    

    【讨论】:

    • 虽然这段代码可能(或可能不会)解决问题,但好的问题还应该解释为什么这段代码有帮助以及它如何解决问题。
    • 这是一个有效的观点,我打算对此进行扩展,但随后它被标记为重复,并带有指向更广泛答案的链接,该答案与我在这里使用的方式相同,所以我就离开了照原样。
    猜你喜欢
    • 2020-12-21
    • 2016-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    • 2013-01-30
    • 1970-01-01
    相关资源
    最近更新 更多