Skip to main content
 首页 » 编程设计

python之如何知道 Python 类型是否具有顺序概念究竟什么是序列

2024年11月01日10txw1958

Python 中的 OrderedDict 不是序列类型,这让我有点吃惊。它有顺序的概念,但不是序列。

Python docs说

There are seven sequence types: strings, Unicode strings, lists, tuples, bytearrays, buffers, and xrange objects.

For other containers see the built in dict and set classes, and the collections module. ...Most sequence types support the following operations....Sequence types also support comparisons.

__contains__对应的那些操作,__add__为拼接,__getitem__为整数(in range(len(foo)))、__len__、__min__、__slice__、index 和 count。 __lt__ 等实现比较。

OrderedDicts 实现了其中一些方法而不是其他方法,可能是因为通过键(如在字典中)或顺序(如在索引中)访问项目的语法糖是相同的。

我知道如果某些东西实现了 __iter__ 我可以遍历它。我怎么才能确定某物是否有订单?我本以为这就是“顺序”的意思,第 n 项总是第 n 项。

请您参考如下方法:

在鸭子打字的世界里,这是一个难题。

两者都是sequences and mapping使用 __getitem__() 分别使用内部索引和键来访问项目。寻找 __getitem__() 方法的可用性并不能区分它们,您需要查看该方法实际做了什么。

对于字典,不可能知道 __getitem__() 的整数参数是索引还是键,所以它总是以映射方式工作。

因此,我认为 dict 根本不是序列,尽管它支持迭代。这同样适用于集合。

查看 collections.abc.Sequence 基类可能是最好的测试。对于自定义类型,只需确保它们派生自该基类即可。