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 中对函数进行深度复制?


- 使用 Cython 将 Python 链接到共享库 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01