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

How can I make a deepcopy of a function in Python?(如何在 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 中对函数进行深度复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)