zoukankan      html  css  js  c++  java
  • 如何判断一个对象是否是可调用对象

    基本上判断python对象是否为可调用的函数,有三种方法:

    1、使用内置的callable函数

    callable(func)

    用于检查对象是否可调用,返回True也可能调用失败,但是返回False一定不可调用

    2、判断对象类型是否是FunctionType

    type(func) is FunctionType
    # 或者
    isinstance(func, FunctionType)

    3、判断对象是否实现__call__方法

    hasattr(func, '__call__')

    例子:

    # 三种验证方式的区别
    from types import FunctionType
    
    class A(object):
    
        @staticmethod
        def f1():
            return 'from f1'
    
        @classmethod
        def f2(cls,*arg):
            return 'from f2'
    
        def f3(self,*arg):
            return 'from f3'
    
    def f4():
        pass
    
    if __name__ == '__main__':
        a=A()
    
        print('静态方法,实例调用验证')
        print(callable(a.f1))     # True
        print(type(a.f1) is FunctionType)  # True
        print(hasattr(a.f1,'__call__'))   # True
    
        print('静态方法,类调用验证')
        print(callable(a.f2))     # True
        print(type(a.f2) is FunctionType)   # False
        print(hasattr(a.f2,'__call__'))   # True
    
        print('类方法验证')
        print(callable(A.f3))   # True
        print(type(A.f3) is FunctionType)   # True
        print(hasattr(A.f3,'__call__'))   # True
    
        print('实例方法验证')
        print(callable(a.f3))  # True
        print(type(a.f3) is FunctionType)  # False
        print(hasattr(a.f3, '__call__'))  # True
    
        print('函数验证')
        print(callable(f4))     # True
        print(type(f4) is FunctionType) # True
        print(hasattr(f4,'__call__'))   # True
    
    """
    通过运行结果,发现三种方法的验证结果并不相同。
    主要是type(func) is FunctionType方法,在验证类方法和实例方法时,会返回False,
    从调试的结果上看,实例方法,和类方法的类型都是<class 'method'>,不是FunctionType,所以会返回False。
    """
    python中分为函数(function)和方法(method),函数是python中一个可调用对象(用户定义的可调用对象,及lambda表达式
    创建的函数,都是函数,其类型都是FunctionType),方法是一种特殊的类函数。
    官方文档中,对于method的定义:
    Methods are always bound to an instance of a user-defined class
    类方法和类进行绑定,实例方法与实例进行绑定,所以两者的类型都是method。
    而静态方法,本身即不和类绑定,也不和实例绑定,不符合上述定义,所以其类型应该是function。

    其中还有需要注意的是,如果一个类实现了__call__方法,那么其实例也会成为一个可调用对象,其类型为创建这个实例的类,而不是函数或方法。
    class MyClass(object):
        def __call__(self, *args, **kwargs):
            return self
    
    if __name__ == '__main__':
        myclass=MyClass()
        print(callable(myclass))    # True
    所以通过类型去判断Python对象是否可调用,需要同时判断是函数(FunctionType)还是方法(MethodType),或者类是否实现__call__方法。
    如果只是单纯判断python对象是否可调用,用callable()方法会更稳妥。
  • 相关阅读:
    XML错误信息Referenced file contains errors (http://www.springframework.org/schema/beans/spring-beans-4.0.xsd). For more information, right click on the message in the Problems View ...
    Description Resource Path Location Type Cannot change version of project facet Dynamic Web Module to 2.3.
    maven创建web报错Cannot read lifecycle mapping metadata for artifact org.apache.maven.plugins:maven-compiler-plugin:maven-compiler-plugin:3.5.1:runtime Cause: error in opening zip file
    AJAX跨域
    JavaWeb学习总结(转载)
    JDBC学习笔记
    Java动态代理之JDK实现和CGlib实现
    (转)看懂UML类图
    spring boot配置使用fastjson
    python3下django连接mysql数据库
  • 原文地址:https://www.cnblogs.com/haiyan123/p/8450483.html
Copyright © 2011-2022 走看看