菜鸟教程 -- 学的不仅是技术,更是梦想!

Python 3 教程
Python3 教程 Python3 简介 Python3 环境搭建 Python3 VScode Python3 基础语法 Python3 基本数据类型 Python3 数据类型转换 Python3 解释器 Python3 注释 Python3 运算符 Python3 数字(Number) Python3 字符串 Python3 列表 Python3 元组 Python3 字典 Python3 集合 Python3 条件控制 Python3 循环语句 Python3 编程第一步 Python3 推导式 Python3 迭代器与生成器 Python3 with Python3 函数 Python3 lambda Python3 装饰器 Python3 数据结构 Python3 模块 Python __name__ Python3 输入和输出 Python3 File Python3 OS Python3 错误和异常 Python3 面向对象 Python3 命名空间/作用域 Python 虚拟环境的创建 Python 类型注解 Python3 标准库概览 Python3 实例 Python 测验

Python3 高级教程

Python3 正则表达式 Python3 CGI编程 Python3 MySQL(mysql-connector) Python3 MySQL(PyMySQL) Python3 网络编程 Python3 SMTP发送邮件 Python3 多线程 Python3 XML 解析 Python3 JSON Python3 日期和时间 Python3 内置函数 Python3 MongoDB Python3 urllib Python uWSGI 安装配置 Python3 pip Python3 operator Python math Python requests Python random Python OpenAI Python 有用的资源 Python AI 绘画 Python statistics Python hashlib Python 量化 Python pyecharts Python selenium 库 Python 爬虫 Python Scrapy 库 Python Markdown Python sys 模块 Python Pickle 模块 Python subprocess 模块 Python queue 模块 Python StringIO 模块 Python logging 模块 Python datetime 模块 Python re 模块 Python csv 模块 Python threading 模块 Python asyncio 模块 Python PyQt Python for 循环 Python while 循环
(追記) (追記ここまで)

Python callable() 函数

Python3 内置函数 Python3 内置函数


callable() 是 Python 中用于检查对象是否可调用的内置函数。

在 Python 中,函数、方法、类等都是可调用的对象。callable() 可以帮助我们在调用之前检查对象是否可以被调用,避免运行时错误。

单词释义: callable 意为"可调用的",表示对象是否可以像函数一样被调用。


基本语法与参数

语法格式

callable(object)

参数说明

  • 参数 object:
    • 类型: 任意对象
    • 描述: 要检查的对象。

函数说明

  • 返回值: 返回布尔值 TrueFalse
  • 注意: 返回 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

运行结果预期:

True
True
True
True
True
False
False
True

代码解析:

  1. 函数、方法、类、lambda 表达式都是可调用的。
  2. 字符串、数字等基本类型不可调用。

示例 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

运行结果预期:

Hello, Tom!
not a function 不可调用
处理点击

callable() 在需要动态调用函数或验证回调函数时非常有用。


Python3 内置函数 Python3 内置函数


AI 思考中...

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /