为什么.copy和.clear方法不是序列抽象基类规范的一部分?

2024-06-16 10:57:26 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:这可能只是一个没有解决的疏忽吗?标准类型文档包括.copy().clear()in the table of methods for mutable sequence types

今天早上我注意到一些奇怪的事情:Python中的list对象>;3.3包括.copy()方法和.clear()方法。但是collections.abcSequenceMutableSequence抽象基类do not include these methods是它们规范的一部分(.clear()当然,作为MS规范的一部分才有意义)

>>> x = [1,2,3]
>>> x.copy()
[1, 2, 3]
>>> x.clear()
>>> x
[]

我的理解是使用MutableSequence的部分原因是to signal to the universewant your object to "act like a ^{}"(除非另有明确说明):

from typing import Sequence

class S(Sequence):
    x = [1, 2, 3]
    def __getitem__(self, item):
        return self.x[item]
    def __len__(self):
        return len(self.x)

然而,完全定义的S类型不能被复制(MS不能被清除),就像list

>>> s = S()
>>> s.copy()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'S' object has no attribute 'copy'

这看起来很奇怪,像大多数这样的事情,可能有一个很好的理由。这是什么


Tags: theto方法inself规范类型object
1条回答
网友
1楼 · 发布于 2024-06-16 10:57:26

在发布问题之后,找到了一个答案——至少是关于copy()——似乎这个问题was discussed很久以前就出现在bug tracker中了。几句名言:

I don't think this is needed nor do I think that it is a good idea to have a copy() method in the ABCs because they know so little about their concrete underlying class (perhaps the backing store in the filesystem or a database).

以及:

The return type of copy() for ABCs feels problematic. MutableMapping doesn't have it either.

正如我所料,这是讨论,似乎有合理的理由背后

GVR的小道消息也值得包括:

I personally despise almost all uses of "copying" (including the entire copy module, both deep and shallow copy functionality).

相关问题 更多 >