如何修改Python中PriorityPerson类的__lt__魔法方法以实现正确排序?
Fixing the PriorityPerson lt Method for Correct Sorting
Let's break down what's wrong with your current __lt__ implementation and fix it to match your sorting rules:
What's Wrong with the Original Code
Your __lt__ method is overly verbose and contains logical errors:
- When comparing objects with different
deficientestates, you incorrectly still check the name—alldeficiente=Trueobjects should come beforedeficiente=Falseones, regardless of their names. - The same-state branches are redundant and in some cases, the return logic is needlessly convoluted (though it might accidentally work, it's hard to maintain).
Correct Implementation
We can simplify the __lt__ logic to directly match your requirements:
- First compare the
deficientestatus:deficiente=Trueobjects are "smaller" (should sort first) thandeficiente=Falseones. - If statuses are identical, fall back to lexicographical sorting by name (just like the base
Personclass).
Here's the revised PriorityPerson class:
class PriorityPerson(Person): def __init__(self, name, deficiencia): super().__init__(name) self.deficiente = deficiencia def __lt__(self, other): # Handle differing deficiente states first if self.deficiente != other.deficiente: # True is considered "less than" False return self.deficiente # Same state: sort by name lex order return self.name < other.name
How This Works
- When
self.deficienteandother.deficientediffer:return self.deficientedoes exactly what we need. Ifselfisdeficiente=TrueandotherisFalse, it returnsTrue(soselfcomes first). IfselfisFalseandotherisTrue, it returnsFalse(soothercomes first). - When states are the same, we just compare names lexicographically, which aligns with your requirement.
Test the Fixed Code
Using your sample input:
p1 = PriorityPerson("John Smith", False) p2 = PriorityPerson("Sam Mendes", False) p3 = PriorityPerson("Grandmother Anne", True) p4 = PriorityPerson("Stephen Hawking", True) p5 = PriorityPerson("Betty Large", True) listaPessoas = [p1,p2,p3,p4, p5] listaPessoas.sort() for p in listaPessoas: print(p)
You'll get the expected output:
Betty Large Grandmother Anne Stephen Hawking John Smith Sam Mendes
内容的提问来源于stack exchange,提问作者Tiago Verissimo
相关产品推荐
相关产品推荐

