I just thought of a really hacky way to do this. This is in the same vein as you originally tried to do. It does not require adding any functions to the class object; It works for any class.
max(((f(obj), obj) for obj in obj_list), key=lambda x: x[0])[1]
I really don't like this, so here is something less short, which does the same thing:
def make_pair(f, obj): return (f(obj), obj) def gen_pairs(f, obj_list): return (make_pair(f, obj) for obj in obj_list) def item0(tup): return tup[0] def max_obj(f, obj_list): pair = max(gen_pairs(f, obj_list), key=item0) return pair[1]
Or you can use this one-line key if obj_list always an indexable object, such as a list:
obj_list[max((f(obj), i) for i, obj in enumerate(obj_list))[1]]
This has the advantage that if there are several objects for which f(obj) returns the same value, you know which one you will get: the one that has the highest index, i.e. last on the list. If you need the earliest from the list, you can do this with a key function.
source share