美文网首页
python callable 函数

python callable 函数

作者: tafanfly | 来源:发表于2018-07-24 11:24 被阅读0次

    官方定义

    Return True if the object argument appears callable, False if not. If this returns true, it is still possible that a call fails, but if it is false, calling object will never succeed. Note that classes are callable (calling a class returns a new instance); class instances are callable if they have a __call__().

    中文解说

    检查对象object是否可调用。如果返回Trueobject仍然可能调用失败;但如果返回False,调用对象object绝对不会成功。类是可调用的,而类的实例实现了__call__()方法才可调用。
    一般函数, 方法, lambda 函数式, 类, 以及实现了 __call__ 方法的类实例, 它都返回 True。

    注意

    callable函数在python2.x版本中都可用。但是在python3.0版本中被移除,而在python3.2以后版本中被重新添加

    用例

    • 函数可调用,整数,字符串,列表,元组,字典等不可调用
    In [1]: callable(1)
    Out[1]: False
    
    In [2]: def test():
       ...:     print 'hello'
       ...:
    
    In [3]: callable(test)
    Out[3]: True
    
    • 类和类内的方法是可调用的
    In [4]: class New(object):
       ...:     def hello(self):
       ...:         print 'Hello'
       ...:
    
    In [5]: a = New()
    
    In [6]: callable(New)
    Out[6]: True
    
    In [7]: callable(a.hello)
    Out[7]: True
    
    In [8]: callable(a)  #不可调用
    Out[8]: False
    
    • 实现了__call__()方法的类实例是可调用
    In [9]: class other(object):
       ...:     def hello(self):
       ...:         print 'Hello'
       ...:     def __call__(self):
       ...:         print 'call the class'
       ...:
    
    In [10]: b = other()
    
    In [11]: callable(other)
    Out[11]: True
    
    In [12]: callable(b.hello)
    Out[12]: True
    
    In [13]: callable(b)  #可调用
    Out[13]: True
    
    • lambda表达式是可调用
    In [14]: f = lambda x : x*x
    
    In [15]: f(3)
    Out[15]: 9
    
    In [16]: callable(f)
    Out[16]: True
    
    

    相关文章

      网友评论

          本文标题:python callable 函数

          本文链接:https://www.haomeiwen.com/subject/hzlemftx.html