class User: def init(self, user_id): self.user_id = user_id
代码语言:javascript复制def __repr__(self):
return 'User({})'.format(self.user_id)
def sort_notcompare(): users = [User(23), User(3), User(99)] print(users) print(sorted(users, key=lambda u: u.user_id))
或者:operator.attrgetter
from operator import attrgetter sorted(users, key=attrgetter('user_id')) [User(3), User(23), User(99)]