在Python类中单独实现每个富排序方法的快捷方式?

2024-04-26 23:05:50 发布

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

我有一个Python类,我想通过它的一个属性来支持rich ordering。当然,我可以简单地实现所有的魔法排序方法,比如__lt____le__等,使用该属性作为键,但这似乎有点麻烦和重复。有没有一种方法可以简单地将该属性定义为排序键一次,然后让Python自动计算出各个比较?你知道吗


Tags: 方法ltle属性定义排序魔法ordering
1条回答
网友
1楼 · 发布于 2024-04-26 23:05:50

如果您使用的是Python3.2或更高版本,那么可以使用functools.total_ordering。你知道吗

Given a class defining one or more rich comparison ordering methods, this class decorator supplies the rest. This simplifies the effort involved in specifying all of the possible rich comparison operations:

The class must define one of __ lt__(), __ le__(), __ gt__(), or __ ge__(). In addition, the class should supply an __ eq__() method.

相关问题 更多 >