简体   繁体   English

如何在 python 中深度复制 function

[英]How to deepcopy a function in python

I need to compute a function in a number of cases, and then to sum over all these cases.我需要在许多情况下计算 function,然后对所有这些情况求和。 I figured one way to do that would be to create either a list, a dictionary or an array of functions, but no matter what I do the previous function is erased in the loop.我想一种方法是创建一个列表、字典或函数数组,但无论我做什么,前面的 function 都会在循环中被删除。

def general_func(r, arg1, arg2):
    return r*arg1*arg2

fun_list = []
for i in range(N):
    arg1_i, arg2_i = my_arr[1:3]
    def local_func(r):
        return general_func(r, arg1_i, arg2_i)
    fun_list.append(local_func)

I have tried a number of things, but no matter what I do, I always end up with a tuple of N times the same function.我尝试了很多东西,但无论我做什么,我总是得到一个 N 倍于相同 function 的元组。

I am also unsure on how I would sum over all functions in the end to keep one big function which would be the sum of all others.我也不确定我最终将如何总结所有功能以保留一个大的 function ,这将是所有其他功能的总和。

Following Samwell's answer, I defined functions in the loop:按照 Samwell 的回答,我在循环中定义了函数:

def local_func(r, arg1_i=arg1_i, arg2_i=arg2_i):

And was able to properly define my array of functions.并且能够正确定义我的函数数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM