How can I make a deepcopy of a function in Python?(如何在 Python 中对函数进行深度复制?)
问题描述
我想在 Python 中制作一个函数的深拷贝.copy 模块没有帮助,根据 documentation,其中说:
I would like to make a deepcopy of a function in Python. The copy module is not helpful, according to the documentation, which says:
此模块不会复制模块、方法、堆栈跟踪、堆栈帧、文件等类型,套接字、窗口、数组或任何类似类型.它会复制"函数和类(浅和深度),通过返回原始对象不变;这与方式兼容这些由 pickle 模块处理.
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.
我的目标是拥有两个具有相同实现但具有不同文档字符串的函数.
My goal is to have two functions with the same implementation but with different docstrings.
def A():
"""A"""
pass
B = make_a_deepcopy_of(A)
B.__doc__ = """B"""
那么如何做到这一点呢?
So how can this be done?
推荐答案
FunctionType 构造函数用于对函数进行深拷贝.
The FunctionType constructor is used to make a deep copy of a function.
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 中对函数进行深度复制?


基础教程推荐
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01