# 排序类定义的实例-sorted-attrgetter

代码：

note:`from operator import attrgetter`

```python
class User:
    def __init__(self,user_id):
        self.user_id = users_id
    def __repr__(self):
        return 'User({})'.format(self.user_id)

print('原始','-'*50)
users=[User(19),User(17),User(18)]
print(users)

print('排序1,key=lambda ui:ui.user_id','-'*50)
order_users=sorted(users,key=lambda ui:ui.user_id)#根据user_id降序
print(order_users)

print('排序2,key=lambda ui:ui.user_id,reverse=True','-'*50)
order_users2=sorted(users,key=lambda ui:ui.user_id,reverse=True)#根据user_id升序
print(order_users2)

print('排序3,key=attrgetter(\'user_id\')','-'*50)

from operator import attrgetter
#根据attrgetter获得迭代对象的属性user_id进行排序
order_users3=sorted(users,key=attrgetter('user_id'))
print(order_users3)
```

结果：

```python
原始 --------------------------------------------------
[User(19), User(17), User(18)]
排序1,key=lambda ui:ui.user_id --------------------------------------------
[User(17), User(18), User(19)]
排序2,key=lambda ui:ui.user_id,reverse=True -------------------------------
[User(19), User(18), User(17)]
排序3,key=attrgetter('user_id') ----------------------------------
[User(17), User(18), User(19)]
```

视频：

```
wait
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://im-qianuxn.gitbook.io/pytorch/ji-suan-ji/python/2.1.4-pai-xu-lei-ding-yi-de-shi-li.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
