gpt4 book ai didi

python-3.x - Python3 deepcopy 的备忘录和 nil 参数的文档不完整和/或循环?

转载 作者:行者123 更新时间:2023-12-05 02:23:01 24 4
gpt4 key购买 nike

有没有人知道 (a) copy.deepcopy()memonil 参数的解释,或者 (b)指向有关它们的真正信息文档的指针?

我在 Pydev 3.7.1 控制台中使用 Python 3.4.1 来试验 copy.deepcopy。在 PyDev 控制台中,代码完成功能告诉我 deepcopy 的语法是 deepcopy(x, memo=None, _nil=[])。我已经在使用 x,但是 memonil 对我来说是新的。

到目前为止,这是我查找有关这两个参数的信息的地方:

  • Python 3.4.1 文档:https://docs.python.org/3/library/copy.html?highlight=deepcopy#copy.deepcopy .这只给我 copy.deepcopy(x) -- 没有 memonil

  • 在 PyDev 控制台中,>>> 帮助(复制)。这给了我 deepcopy(x, memo=None, _nil=[])对任意 Python 对象的深度复制操作。有关详细信息,请参阅模块的 __ doc __ 字符串。 所以我接下来查看...

  • D:\Python34\lib\copy.py 的文档字符串。文档字符串让我引用文档字符串。唉……

  • copy.py 的 333 行代码中。我承认我还没到阅读代码就能提供信息的地步。

  • 在 StackOverflow 和 Web 上搜索。我设法找到了一些关于记忆化概念的一般信息(这显然是一种保留操作结果的方法,这样操作就不需要在下次调用时从头开始执行)。我还找到了一些关于 Python 2.4 的信息,“Params memo 和 nil 用于递归深度复制,它们的默认值为 None 和空列表”。( http://www.cheat-sheets.org/saved-copy/PQRC-2.4-A4-latest.pdf ,除其他外)

引用的 2.4 备忘单让我猜测 memonil 可能用于限制 deepcopy 递归到源元素的嵌套子元素的深度。但这只是一个猜测。

所以我仍在寻找能够真正解释如何使用参数的内容。

(如果 Python 文档系统包含不完整的解释,我是否应该考虑提交文档错误?)

预先感谢您的帮助。

最佳答案

来自 deepcopy 文档的下方:

Two problems often exist with deep copy operations that don’t exist with shallow copy operations:

  • Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop.
  • Because deep copy copies everything it may copy too much, e.g., administrative data structures that should be shared even between copies.

The deepcopy() function avoids these problems by:

  • keeping a “memo” dictionary of objects already copied during the current copying pass; and
  • letting user-defined classes override the copying operation or the set of components copied.

...

In order for a class to define its own copy implementation, it can define special methods __copy__() and __deepcopy__(). The former is called to implement the shallow copy operation; no additional arguments are passed. The latter is called to implement the deep copy operation; it is passed one argument, the memo dictionary. If the __deepcopy__() implementation needs to make a deep copy of a component, it should call the deepcopy() function with the component as first argument and the memo dictionary as second argument.

这就是 memo 的用途。它会跟踪已经复制的内容。

_nil 是一个实现细节。它被使用一次,作为 memo.get 调用的标记值。它是默认参数这一事实是一种微优化,将其设为默认参数所节省的少量时间可能不会超过在签名中看到它所带来的轻微混淆。

关于python-3.x - Python3 deepcopy 的备忘录和 nil 参数的文档不完整和/或循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25735224/

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