Collaborating with max
,
min
and sort
The min
and max
functions can interact with our classes in relatively simple ways.
Similarly, the sort
method of a list can also
interact with our new class definitions. In all three cases, a keyword
parameter of
key
can be used to
control which attributes are used for determining minimum, maximum or
sort order.
The
key
parameter must be given a function,
and that function is evaluated on each item that is being compared.
Here's a quick example.
class Boat( object ):
def __init__( self, name, loa ):
self.name= name
self.loa= loa
def byName( aBoat ):
return aBoat.name
def byLOA( aBoat ):
return aBoat.loa
fleet = [ Boat("KaDiMa", 18 ), Boat( "Emomo", 21 ), Boat("Leprechaun", 30 ) ]
first= min( fleet, key=byName )
print "Alphabetically First:", first
longest= max( fleet, key=byLOA )
print "Longest:", longest
As min
, max
or sort
traverse the sequence doing comparisons among the objects, they evaluate
the key
function we provided. In this example, the
provided function simply selects an attribute. Clearly the functions
could do calculations or other operations on the objects.