官方定义
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是否可调用。如果返回True
,object仍然可能调用失败;但如果返回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
网友评论