Created
August 21, 2016 18:58
-
-
Save burakdede/91791281a17ed3a1142b38a63bbda372 to your computer and use it in GitHub Desktop.
attrgetter for custom class fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
[User(1), User(10), User(19), User(29)] | |
[User(1), User(10), User(19), User(29)] | |
""" | |
from operator import attrgetter | |
class User: | |
def __init__(self, user_id): | |
self.user_id = user_id | |
def __repr__(self): | |
return "User({})".format(self.user_id) | |
users = [User(19), User(29), User(1), User(10)] | |
sorted_users = sorted(users, key=lambda u: u.user_id) | |
attr_sorted_users = sorted(users, key=attrgetter("user_id")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment