问题描述:按照模型的@property降序排序不起作用。
解决方法示例:
假设有一个Person模型类,其中包含一个名为age的属性使用@property装饰器定义,我们希望按照age的降序对Person对象列表进行排序。
class Person:
def __init__(self, name, age):
self.name = name
self._age = age
@property
def age(self):
return self._age
@age.setter
def age(self, value):
self._age = value
# 创建Person对象列表
people = [
Person("Alice", 25),
Person("Bob", 30),
Person("Charlie", 20)
]
# 按照age降序排序
sorted_people = sorted(people, key=lambda x: x.age, reverse=True)
# 打印排序结果
for person in sorted_people:
print(person.name, person.age)
如果按照上述代码进行排序,你会发现排序结果并没有按照age的降序排列。这是因为属性装饰器@property本身并没有提供排序功能,sorted函数只会对对象的属性进行排序,而不会调用属性的getter方法。
为了解决这个问题,我们可以修改排序的key函数,直接使用对象的_age属性进行排序:
sorted_people = sorted(people, key=lambda x: x._age, reverse=True)
这样修改之后,将按照age的降序排列列表中的Person对象。
请注意,直接访问对象的私有属性可能不符合面向对象编程的最佳实践。可以考虑在模型类中添加一个自定义的比较方法,通过该方法间接比较属性值。
class Person:
# ...
def compare_age(self):
return self.age
sorted_people = sorted(people, key=lambda x: x.compare_age(), reverse=True)
通过调用compare_age方法来进行属性比较,可以更好地封装对象的属性。
上一篇:按照某种模式去除重复元素失败。
下一篇:按照模型关联返回的结果进行排序