Python 如何让一个函数记住它的调用次数和历史参数
技术百科
冷漠man
发布时间:2026-01-16
浏览: 次 可用函数属性、闭包或类实现函数记忆调用次数和历史参数:方法一为直接添加函数属性,简单但需手动初始化;方法二用闭包封装状态,更安全且支持多实例;方法三用类包装,最灵活,便于扩展重置、查询等功能。
可以用函数属性、闭包或类来实现函数“记住”调用次数和历史参数。最简洁常用的是给函数动态添加属性,或用闭包封装状态。
方法一:直接给函数加属性(简单直接)
Python 函数是对象,支持动态绑定属性。在函数内部或外部记录调用信息即可:
- 首次调用前,手动初始化
func.call_count = 0和func.history = [] - 每次调用时,在函数体内递增计数、追加参数(如
func.history.append(args)) - 注意:需确保初始化只做一次,推荐在定义后立即设置
示例:
def my_func(x, y):
my_func.call_count += 1
my_func.history.append((x, y))
return x + y
my_func.call_count = 0
my_func.history = []
调用两次后,my_func.call_count 为 2,my_func.history 类似 [(1, 2), (3, 4)]。
方法二:用闭包封装状态(更安全,避免污染函数名空间)
把计数器和历史列表放在外层函数作用域中,内层函数

- 状态变量不会暴露在全局或函数对象上,更干净
- 适合需要多个独立“可记忆函数”的场景(每个闭包有自己的状态)
- 返回的函数保持原调用方式,对使用者透明
示例:
def make_tracked_func(func):
count = 0
history = []
def tracked(*args, **kwargs):
nonlocal count
count += 1
history.append((args, kwargs))
return func(*args, **kwargs)
tracked.call_count = lambda: count
tracked.get_history = lambda: history.copy()
return tracked
使用
add = make_tracked_func(lambda x, y: x + y)
add(1, 2) # 调用一次
add(3, 4) # 再调用一次
print(add.call_count()) # → 2
print(add.get_history()) # → [((1, 2), {}), ((3, 4), {})]
方法三:用类包装(最灵活,支持重置、筛选、持久化等)
当需要更多控制(比如清空历史、按条件查询、保存到文件),类是最自然的选择:
- 把函数逻辑作为实例方法或传入的 callable
- 用实例属性
self.count和self.history管理状态 - 可轻松添加
.reset()、.last_call()、.calls_since(n)等方法
示例(简化版):
class TrackedFunction:
def __init__(self, func):
self.func = func
self.count = 0
self.history = []
def __call__(self, *args, **kwargs):
self.count += 1
self.history.append({'args': args, 'kwargs': kwargs, 'result': self.func(*args, **kwargs)})
return self.history[-1]['result']
def reset(self):
self.count = 0
self.history.clear()使用
tracked_add = TrackedFunction(lambda x, y: x + y)
tracked_add(1, 2)
print(tracked_add.count) # → 1
print(tracked_add.history[0]['result']) # → 3
小提醒:避免常见坑
使用这些方法时要注意:
- 多线程下需加锁(
threading.Lock),否则count += 1非原子操作可能出错 - 历史参数含可变对象(如 list、dict)时,建议深拷贝再存,防止后续修改影响记录
- 闭包中的
nonlocal只支持单层嵌套;若需多层,改用类或字典容器 - 函数属性方式不适用于 lambda(lambda 不能赋属性),优先选闭包或类
# 的是
# 放在
# 自己的
# 多个
# python
# 首次
# 等功能
# 时要
# 可以用
# app
# 两次
# 对象
# 线程
# 多线程
# 封装
# 作用域
# 闭包
# history
# count
# Lambda
# print
# append
# 来实现
相关栏目:
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
AI推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
SEO优化<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
技术百科<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
谷歌推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
百度推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
网络营销<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
案例网站<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
精选文章<?muma echo $count; ?>
】
相关推荐
- php能跑在stm32上吗_php在stm32微控
- 如何在Golang中使用闭包_封装变量与函数作用域
- 如何使用Golang安装依赖库_管理模块和第三方包
- Win11键盘快捷键大全_Windows 11常用
- Windows如何设置登录时的欢迎屏幕背景?(锁屏
- 如何在Golang中实现微服务服务拆分_Golan
- Win11怎么关闭搜索历史 Win11清除搜索框最
- c++怎么编写动态链接库dll_c++ __dec
- 如何使用正则表达式提取以编号开头、后接多个注解的逻
- Win11怎么设置任务栏大小_Windows11注
- 如何用正则表达式精确匹配最多含一个换行符的起止片段
- Windows10如何彻底关闭自动更新_Win10
- Python函数缓存机制_lru_cache解析【
- Mac如何整理桌面文件_Mac使用堆栈功能一键整理
- Win10怎样清理C盘爱奇艺缓存_Win10清理爱
- php下载安装后swoole扩展怎么安装_异步框架
- Win11搜索不到蓝牙耳机怎么办 Win11蓝牙驱
- 如何使用Golang开发简单的聊天室消息存储_Go
- Go 中实现 Python urllib.quot
- Win11怎么把图标拖到任务栏_Win11固定应用
- c++如何用AFL++进行模糊测试 c++ Fuz
- php文件怎么变mp4保存_php输出视频流保存为
- Python多线程使用规范_线程安全解析【教程】
- Win11截图快捷键是什么_Win11自带截图工具
- Win11怎么修复系统文件_使用sfc命令修复Wi
- php485返回数据不完整怎么办_php485数据
- Win11如何暂停系统更新 Win11暂停更新最长
- Win11怎么关闭右下角弹窗_Win11拦截系统通
- Windows电脑如何截屏?(四种快捷方法)
- Windows11怎么自定义任务栏_Windows
- Win11关机界面怎么改_Win11自定义关机画面
- Win11怎么查看电脑配置_Win11硬件配置详细
- Windows11如何设置专注助手_Windows
- Win10如何卸载WindowsDefender_
- 如何在Golang中实现基础配置管理功能_Gola
- 如何在Golang中定义接口_抽象方法和多态实现
- Mac的“预览”如何合并多个PDF_Mac文件处理
- Bpmn 2.0的XML文件怎么画流程图
- 如何在 IIS 上为 ASP.NET 6 应用排除
- Win11怎么设置闹钟_Windows 11时钟应
- 如何使用Golang实现错误包装与传递_Golan
- Win11怎么设置组合键快捷方式_Windows1
- 如何使用Golang实现Web表单数据绑定_自动映
- Python高性能计算项目教程_NumPyCyth
- Windows10如何更改桌面背景_Win10个性
- Win11怎么设置ipv4地址_Windows 1
- c++中如何使用虚函数实现多态_c++多态性实现原
- Windows10怎么备份注册表_Windows1
- Win11系统更新后黑屏怎么办 Win11更新黑屏
- php8.4如何调用com组件_php8.4win

QQ客服