python - 如何在 Python3 中将函数列表保存为对象
问题描述
我正在研究过滤器。对于每种情况,我都有一个处理输入数据的函数列表,这些函数因情况而异。我想序列化并保存这样的函数列表,以便我可以为每种情况加载和使用函数。我尝试使用 pickle 将列表转储为 pkl 文件,但如果我删除函数的定义,则无法加载它。为了更明确地传递它,它像这样运行
def a1(obj):
pass
def a2(obj):
pass
def b1(obj):
pass
def b2(obj):
pass
a_func = [a1, a2]
b_func = [b1, b2]
if obj.flag == 1:
for fun in a_func:
fun(obj)
elif obj.flag == 2:
for fun in b_func:
fun(obj)
我想保存这样的a_func
和b_func
作为pkl文件左右。我不知道如何将它们保存为 py. 我需要处理100多个案例,每个案例可能需要10个左右的功能,其中大部分是通用的。我不想手动输入它们。
解决方案
在这里,您可以尝试这样,exec()
在列表中使用和存储函数的字符串名称:
class obj:
def __init__(self):
self.flag = 1
def a1(obj):
pass
def a2(obj):
pass
def b1(obj):
pass
def b2(obj):
pass
a_func = ['a1', 'a2']
b_func = ['b1', 'b2']
objg = obj()
if objg.flag == 1:
for fun in a_func:
exec('{x}(objg)'.format(x=fun))
elif objg.flag == 2:
for fun in b_func:
exec('{x}(objg)'.format(x=fun))
推荐阅读
- oracle - 如何从 PLSQL Oracle 过程中删除数据或清空游标?
- blazor - 保护 blazor 客户端应用程序的有效程序是什么?
- forms - 有没有办法只接受特定的文件名称而不是文件类型?
- nginx - 如何在来自 nginx 代理服务器的上游请求中传递标头?
- ios - 如何在快速解析时检查用户是否已在注册时使用电话号码或新用户注册的条件
- google-data-studio - Datastudio:是否可以将表格用作ie的数据源。饼形图?
- bash - 直接使用脚本或命令删除 solaris 上的主机文件条目
- google-apps-script - 谷歌表格数据验证下拉菜单显示值但粘贴公式?
- javascript - exif-js 方向在 android 上总是返回 0 但在桌面上工作
- sql-server - 如何在 SQL Server 中缩小 mdf 文件而不会出错?