gpt4 book ai didi

python - 如何在 Python 中对函数进行深度复制?

转载 作者:IT老高 更新时间:2023-10-28 20:44:02 26 4
gpt4 key购买 nike

我想在 Python 中制作一个函数的深拷贝。根据 documentationcopy 模块没有帮助。 ,上面写着:

This module does not copy types like module, method, stack trace, stack frame, file, socket, window, array, or any similar types. It does “copy” functions and classes (shallow and deeply), by returning the original object unchanged; this is compatible with the way these are treated by the pickle module.

我的目标是拥有两个具有相同实现但具有不同文档字符串的函数。

def A():
"""A"""
pass

B = make_a_deepcopy_of(A)
B.__doc__ = """B"""

那么如何做到这一点呢?

最佳答案

FunctionType 构造函数用于制作函数的深拷贝。

import types
def copy_func(f, name=None):
return types.FunctionType(f.func_code, f.func_globals, name or f.func_name,
f.func_defaults, f.func_closure)

def A():
"""A"""
pass
B = copy_func(A, "B")
B.__doc__ = """B"""

关于python - 如何在 Python 中对函数进行深度复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6527633/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com