Python callable() 函数
callable() 是 Python 中用于检查对象是否可调用的内置函数。
在 Python 中,函数、方法、类等都是可调用的对象。callable() 可以帮助我们在调用之前检查对象是否可以被调用,避免运行时错误。
单词释义: callable 意为"可调用的",表示对象是否可以像函数一样被调用。
基本语法与参数
语法格式
callable(object)
参数说明
- 参数 object:
- 类型: 任意对象
- 描述: 要检查的对象。
函数说明
- 返回值: 返回布尔值
True或False。 - 注意: 返回 True 不代表调用一定会成功,只是表示对象可以被调用。
实例
示例 1:检查各种对象
实例
# 函数
def my_func():
pass
print(callable(my_func)) # 输出: True
# 方法
class MyClass:
def my_method(self):
pass
obj = MyClass()
print(callable(obj.my_method)) # 输出: True
# 类(类可以被调用来创建实例)
print(callable(MyClass)) # 输出: True
# 内置函数
print(callable(len)) # 输出: True
print(callable(print)) # 输出: True
# 字符串(不可调用)
print(callable("hello")) # 输出: False
# 数字(不可调用)
print(callable(123)) # 输出: False
# Lambda 表达式
my_lambda = lambda x: x * 2
print(callable(my_lambda)) # 输出: True
def my_func():
pass
print(callable(my_func)) # 输出: True
# 方法
class MyClass:
def my_method(self):
pass
obj = MyClass()
print(callable(obj.my_method)) # 输出: True
# 类(类可以被调用来创建实例)
print(callable(MyClass)) # 输出: True
# 内置函数
print(callable(len)) # 输出: True
print(callable(print)) # 输出: True
# 字符串(不可调用)
print(callable("hello")) # 输出: False
# 数字(不可调用)
print(callable(123)) # 输出: False
# Lambda 表达式
my_lambda = lambda x: x * 2
print(callable(my_lambda)) # 输出: True
运行结果预期:
True True True True True False False True
代码解析:
- 函数、方法、类、lambda 表达式都是可调用的。
- 字符串、数字等基本类型不可调用。
示例 2:实际应用
实例
# 安全调用函数
def safe_call(obj, *args, **kwargs):
if callable(obj):
return obj(*args, **kwargs)
else:
return f"{obj} 不可调用"
# 测试
def greet(name):
return f"Hello, {name}!"
print(safe_call(greet, "Tom")) # 输出: Hello, Tom!
print(safe_call("not a function")) # 输出: not a function 不可调用
# 在 API 设计中使用
class EventHandler:
def __init__(self):
self.handlers = {}
def register(self, event, handler):
if not callable(handler):
raise TypeError("handler 必须是可调用的")
self.handlers[event] = handler
def trigger(self, event, *args):
if event in self.handlers:
return self.handlers[event](*args)
handler = EventHandler()
handler.register("click", lambda: "处理点击")
print(handler.trigger("click")) # 输出: 处理点击
# 注册一个不可调用的对象会报错
# handler.register("error", "not callable") # 抛出 TypeError
def safe_call(obj, *args, **kwargs):
if callable(obj):
return obj(*args, **kwargs)
else:
return f"{obj} 不可调用"
# 测试
def greet(name):
return f"Hello, {name}!"
print(safe_call(greet, "Tom")) # 输出: Hello, Tom!
print(safe_call("not a function")) # 输出: not a function 不可调用
# 在 API 设计中使用
class EventHandler:
def __init__(self):
self.handlers = {}
def register(self, event, handler):
if not callable(handler):
raise TypeError("handler 必须是可调用的")
self.handlers[event] = handler
def trigger(self, event, *args):
if event in self.handlers:
return self.handlers[event](*args)
handler = EventHandler()
handler.register("click", lambda: "处理点击")
print(handler.trigger("click")) # 输出: 处理点击
# 注册一个不可调用的对象会报错
# handler.register("error", "not callable") # 抛出 TypeError
运行结果预期:
Hello, Tom! not a function 不可调用 处理点击
callable() 在需要动态调用函数或验证回调函数时非常有用。
Python3 内置函数
点我分享笔记