python --- Python中的callable 函数

时间:2023-03-08 19:55:24

python --- Python中的callable 函数

转自: http://archive.cnblogs.com/a/1798319/

Python中的callable 函数

callable 函数, 可以检查一个对象是否是可调用的 (无论是直接调用或是通过 apply). 对于函数, 方法, lambda 函式, 类, 以及实现了 _ _call_ _ 方法的类实例, 它都返回 True.

def dump(function):if callable(function):print function, “is callable”else:print function, “is *not* callable”class A:def method(self, value):return valueclass B(A):def _ _call_ _(self, value):return valuea = A()b = B()dump(0) # simple objectsdump(”string”)dump(callable)dump(dump) # functiondump(A) # classesdump(B)dump(B.method)dump(a) # instancesdump(b)dump(b.method)0 is *not* callablestring is *not* callable<built-in function callable> is callable<function dump at 8ca320> is callableA is callableB is callable<unbound method A.method> is callable<A instance at 8caa10> is *not* callable<B instance at 8cab00> is callable<method A.method of B instance at 8cab00> is callable注意类对象 (A 和 B) 都是可调用的; 如果调用它们, 就产生新的对象(类实例). 但是 A 类的实例不可调用, 因为它的类没有实现 _ _call_ _ 方法.你可以在 operator 模块中找到检查对象是否为某一内建类型(数字, 序列, 或者字典等) 的函数. 但是, 因为创建一个类很简单(比如实现基本序列方法的类), 所以对这些 类型使用显式的类型判断并不是好主意.在处理类和实例的时候会复杂些. Python 不会把类作为本质上的类型对待; 相反地, 所有的类都属于一个特殊的类类型(special class type), 所有的类实例属于一个特殊的实例类型(special instance type).这意味着你不能使用 type 函数来测试一个实例是否属于一个给定的类; 所有的实例都是同样 的类型! 为了解决这个问题, 你可以使用 isinstance 函数,它会检查一个对象是 不是给定类(或其子类)的实例. Example 1-15 展示了 isinstance 函数的使用. 
def dump(function):

if callable(function): 
print function, “is callable” 
else: 
print function, “is *not* callable” 
class A: 
def method(self, value): 
return value 
class B(A): 
def _ _call_ _(self, value): 
return value 
a = A() 
b = B() 
dump(0) # simple objects 
dump(”string”) 
dump(callable) 
dump(dump) # function 
dump(A) # classes 
dump(B) 
dump(B.method) 
dump(a) # instances 
dump(b) 
dump(b.method) 
0 is *not* callable 
string is *not* callable 
<built-in function callable> is callable 
<function dump at 8ca320> is callable 
A is callable 
B is callable 
<unbound method A.method> is callable 
<A instance at 8caa10> is *not* callable 
<B instance at 8cab00> is callable 
<method A.method of B instance at 8cab00> is callable 
注意类对象 (A 和 B) 都是可调用的; 如果调用它们, 就产生新的对象(类实例). 但是 A 类的实例不可调用, 因为它的类没有实现 _ _call_ _ 方法.