>>> class MyClass:
... def __init__(self, value):
... self.value = value
... def __repr__(self):
... return 'MyClass({0.value})'.format(self)
... def key_function(self):
... return -self.value
...
>>> my_list = [MyClass(2), MyClass(1), MyClass(3)]
>>> my_list
[MyClass(2), MyClass(1), MyClass(3)]
>>> sorted(my_list, key=lambda mc: mc.value)
[MyClass(1), MyClass(2), MyClass(3)]
>>> min(my_list, key=lambda mc: mc.value) # by attribute
MyClass(1)
>>> sorted(my_list, key=lambda mc: mc.key_function()) # by method call
[MyClass(3), MyClass(2), MyClass(1)]
>>> sorted(my_list, key=MyClass.key_function) # using unbound method
[MyClass(3), MyClass(2), MyClass(1)]
更新
>>> class MyClass:
... def __init__(self, value):
... self.value = value
... def __repr__(self):
... return 'MyClass({0.value})'.format(self)
... def delta(self, other):
... return abs(self.value - other.value)
...
>>> def foo(a_list, key):
... return [key(a, b) for a, b in zip(a_list, a_list[1:])]
...
>>> my_list = [MyClass(1), MyClass(10), MyClass(100)]
>>> print foo(my_list, key=lambda x, y: abs(x.value - y.value)) # Using lambda
[9, 90]
>>> print foo(my_list, key=MyClass.delta) # Using unbound method
[9, 90]