Original address: Http://docs.pythontab.com/python/python3.4/controlflow.html#tut-functions
Functions can be called in the form of keyword arguments , such as keyword = value . For example, the following function:
defParrot (Voltage, state='a stiff', action='Voom', type='Norwegian Blue'): Print("--This parrot wouldn ' t", Action, end=' ') Print("If you put", Voltage,"volts through it.") Print("--lovely plumage, the", type)Print("--It ' s", state,"!")
Accepts a required parameter (voltage) and three optional parameters (state, action, and type).
Can be called in the following ways:
Parrot (1000)#1 positional argumentParrot (voltage=1000)#1 keyword ArgumentParrot (voltage=1000000, action='Vooooom')#2 keyword ArgumentsParrot (action='Vooooom', voltage=1000000)#2 keyword ArgumentsParrot'a million','Bereft of life',' Jump')#3 Positional argumentsParrot'a thousand', state='pushing up the daisies')#1 positional, 1 keyword
However, the following types of calls are not valid:
Parrot () # required argument m Issing Parrot (voltage=5.0, " dead ") # parrot (, voltage=220) # duplicate value for the same argument parrot (Actor= john Cleese ) # unknown keyword argument
When a parameter such as **name is introduced, it receives a dictionary (see typesmapping ), which contains all the keyword parameters that do not appear in the formal parameter list. This may also be combined with a formal parameter such as *name (detailed in the next section), which receives a tuple (described in detail in the next sections) and contains all the parameter values that are not present in the formal parameter list. ( *name must appear before **name ) For example, we define a function like this:
defCheeseshop (Kind, *arguments, * *keywords):Print("-- don't have any", Kind,"?") Print("--I ' m Sorry, we ' re all out of", kind) forArgincharguments:Print(ARG)Print("-"* 40) Keys=Sorted (Keywords.keys ()) forkwinchKeys:Print(KW,":", keywords[kw])
It can be called like this:
Cheeseshop ("Limburger","It ' s very runny, sir.", "It ' s really very, very runny, sir.", shopkeeper="Michael Palin", Client="John Cleese", Sketch="Cheese Shop Sketch")
Of course it will print as follows:
- does any Limburger? --I 'm Sorry, we'reAll out of Limburgerit's very runny, sir. It's really very, very runny, sir. ----------------------------------------client:john cleeseshopkeeper:michael Palinsketch:cheese Shop sketch
Note the sort () method is called before the contents of the keyword parameter dictionary are printed. Otherwise, the order in which the parameters are printed is undefined
Python keyword parameters