functions can interact with our classes in relatively simple ways.
sort method of a list can also
interact with our new class definitions. In all three cases, a keyword
can be used to
control which attributes are used for determining minimum, maximum or
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 ):
def byName( aBoat ):
def byLOA( aBoat ):
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
max or sort
traverse the sequence doing comparisons among the objects, they evaluate
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.