Created
June 20, 2013 09:54
-
-
Save justinfay/5821587 to your computer and use it in GitHub Desktop.
stupidly unpythonic methodcaller example
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
>>> from operator import methodcaller | |
>>> from random import randint | |
>>> class Foo(object): | |
... def __init__(self): | |
... self.number = randint(0, 10) | |
... def get_number(self): | |
... return self.number | |
... | |
>>> lfoos = [Foo() for i in xrange(10)] | |
>>> for foo in lfoos: | |
... print foo.number | |
... | |
4 | |
5 | |
9 | |
5 | |
10 | |
10 | |
0 | |
3 | |
0 | |
6 | |
>>> f = methodcaller('get_number') | |
>>> for foo in sorted(lfoos, key=lambda x: f(x)): | |
... print foo.number | |
... | |
0 | |
0 | |
3 | |
4 | |
5 | |
5 | |
6 | |
9 | |
10 | |
10 | |
>>> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment