Last active
December 16, 2015 13:59
-
-
Save Problematic/5445550 to your computer and use it in GitHub Desktop.
Getters make this more complicated
This file contains hidden or 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
| class SomeObject(object): | |
| def __init__(self, foo, bar): | |
| self.foo = foo | |
| self.bar = bar | |
| def get_foo(self): | |
| return self.foo | |
| def get_bar(self): | |
| return self.bar | |
| def __repr__(self): | |
| return '{0} : {1}'.format(self.foo, self.bar) | |
| obj_list = [SomeObject(1, 'z'), SomeObject(2, 'y'), SomeObject(3, 'x')] | |
| def sortify(list, method): | |
| return sorted(list, key=lambda o: getattr(o, method)()) | |
| print sortify(obj_list, 'get_bar') |
This file contains hidden or 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
| # simpler and more pythonic, ah yeah | |
| class SomeObject(object): | |
| def __init__(self, foo, bar): | |
| self._foo = foo | |
| self._bar = bar | |
| @property | |
| def foo(self): | |
| return self._foo | |
| @property | |
| def bar(self): | |
| return self._bar | |
| def __repr__(self): | |
| return '{0} : {1}'.format(self.foo, self.bar) | |
| obj_list = [SomeObject(1, 'z'), SomeObject(2, 'y'), SomeObject(3, 'x')] | |
| def sortify(list, property): | |
| return sorted(list, key=lambda o: getattr(o, property)) | |
| print sortify(obj_list, 'bar') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment