Python: how key is passed into the function with d

2019-08-25 11:02发布

问题:

I'm confused in this code, the allmax passes hand_rank function as the key, but in the definition of allmax, it sets the key to be None, then how the hand_rank passed to this allmax function?

def poker(hands):
    "Return a list of winning hands: poker([hand,...]) => [hand,...]"         
    return allmax(hands, key=hand_rank)


def allmax(iterable, key=None):
    "Return a list of all items equal to the max of the itterable."
    result, maxval = [],None
    key = key or (lambda x:x)
    for x in iterable:
        xval = key(x)
        if not result or xval > maxval:
            result,maxval = [x],xval
        elif xval == maxval:
            result.append(x)
    return result

回答1:

That's a default parameter. key would only default to None, if hand_rank was never passed, or was passed empty. You can set a default parameter to be pretty much anything,

def allmax(iterable, key=[])

However in this case, it looks like you want to avoid updating an empty list. If key was set to [ ], it would add to the list on later calls, rather than start with a fresh list.

Here's a good explanation of mutable default parameters, and why None is used to stop unexpected behaviour. And here is someone else on Stack Overflow having the empty list parameter problem.



回答2:

Default value for parameter in the function definition is used only if that function is called without that parameter.

Very simple example for understanding it:

The definition:

def print_it( message = "Hello!" ):
    print( message)

Calling it without a parameter:

print_it();                          # The default value will be used

gives the output

Hello!

Calling it with a parameter

print_it( "Give me your money!" )    # The provided value will be used

gives the output

"Give me your money!"

The default value is in this case totally ignored.



标签: python key max