首页 > 解决方案 > 如何在 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_funcb_func作为pkl文件左右。我不知道如何将它们保存为 py. 我需要处理100多个案例,每个案例可能需要10个左右的功能,其中大部分是通用的。我不想手动输入它们。

标签: python

解决方案


在这里,您可以尝试这样,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))

推荐阅读