我想用 Python 深度复制一个函数。根据 documentation,复制 模块没有帮助。 ,它说:
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/39353158/