在python中对类实例进行排序 [英] Sorting class instances in python
问题描述
python 2.7用什么对普通类实例进行排序?我对默认的排序行为感兴趣.
What does python 2.7 use to sort vanilla class instances? I'm interested in the default sorting behavior.
假设我有课
class S():
pass
然后,我可以创建几个实例,并对它们进行排序:
Then I can create a couple of instances, and sort them:
a = S(); b = S(); c = S()
l = [(a,'a'), (b,'b') ,(c, 'c')]
sorted(l)
这将打印一些排序的对象.现在我有一个两部分的问题:
This will print some sorting of the objects. Now I have a two part question:
- python是否使用对象的
__hash__()
,并因此使用它们的id()
? - 是否可以覆盖
__hash__()
来影响排序行为?
- Is python using the objects'
__hash__()
, and thus theirid()
? - Is it possible to override
__hash__()
to influence the sorting behavior?
推荐答案
Python的排序算法专门使用小于"测试比较项目,该测试可以使用__cmp__()
特殊方法(现已弃用)或
Python's sort algorithm exclusively compares items using a "less than" test, which can be implemented either using the __cmp__()
special method (now deprecated) or __lt__()
on the class.
在没有关于如何比较两个对象的任何特定说明的情况下,与您的情况相同,id()
用于同类型的对象(而不是哈希).
In the absence of any specific instruction on how to compare two objects, the id()
is used (not the hash) for objects of the same type, as in your case.
这篇关于在python中对类实例进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!