当一个对象为可被调用对象时,callable(object)返回为True,否则为False:
Python中的对象有可被调用和不可被调用之分。
def func_test():
print("func_test run")
class class_test():
def __init__(self):
pass
# func_test is callable return True
print("func_test is callable return:%s" % callable(func_test))
# class_test() is not callable return False
print("class_test() is not callable return:%s" % callable(class_test()))
a = class_test()
# a is not callable return False
print("a is not callable return:%s" % callable(a))
print("this means the instance is not callable")
输出
func_test is callable return:True
class_test() is not callable return:False
a is not callable return:False
this means the instance is not callable
上面的例子说明,实例是不可以被调用的。实际中写代码时可能会遇到需要调用实例。
python 中的__call__方法可以解决这个问题
class class_test():
def __init__(self):
print("run class __init__")
def __call__(self):
print("run class __call__")
print("class_test() is not callable return:%s" % callable(class_test()))
class_test()
a = class_test()
print("a is not callable return:%s" % callable(a))
a()
输出
run class __init__
class_test() is not callable return:True
run class __init__
run class __init__
a is not callable return:True
run class __call__