Reputation: 377
So I have a working sorting algorithm in Python. (Its exact contents are irrelevant to this question.) It uses a list called 'people' containing class instances, and the function is hard-coded to sort that list by a specific attribute, 'wealth'.
def my_sort(seq):
# sorts by seq[n].wealth
...
my_sort(people)
Now, I'd like to generalize the function so I could sort by any attribute.
def my_sort2(seq, key):
# sorts by seq[n].key
...
my_sort2(people, wealth)
But this, of course, throws an error, because it doesn't know to consider 'wealth' as a class attribute. So, how is this possible to do?
Upvotes: 2
Views: 178
Reputation: 500933
You could pass the name of the attribute:
def my_sort2(seq, keyname):
sort by getattr(seq[n], keyname)
my_sort2(people, 'wealth')
or a getter functor:
def my_sort2(seq, keyfunc):
sort by keyfunc(seq[n])
my_sort2(people, operator.attrgetter('wealth'))
I prefer the latter approach as it is more generic. For example, it easily allows for computed keys.
Upvotes: 10
Reputation: 35089
The generic attribute getter function getattr
should work:
gettattr(obj, name)
Upvotes: 1