Parameters : Positional arguments 、 Key parameters 、 Default parameters
Positional arguments : take Python The parameter with fixed position in is called position parameter .
>>> def myfunc(s, vt, o):
return ''.join((o, vt, s))
>>> myfunc(' I ', ' I hit ', ' Little turtle ')
' Little turtle hit me '
>>> myfunc(' Little turtle ', ' I hit ', ' I ' )
' I shot a little turtle '
Key parameters : In the case of many parameters , Remembering parameter positions is a bit annoying , You can use keyword parameters to solve problems .
>>> myfunc(o=' I ', vt=' I hit ', s=' Little turtle ')
' I shot a little turtle '
>>> myfunc(o=' I ',' Steamed ', ' Little turtle ')
SyntaxError: positional argument follows keyword argument
Rules when positional parameters and keyword parameters are used at the same time , The location parameter must precede the keyword parameter .
Default parameters : Allow function parameters to specify default values when they are defined , And the default value should be placed at the end . If you reassign , You can replace the default value .
>>> def myfunc(s, vt, o=' Little turtle '):
return ''.join((o, vt, s))
>>> myfunc(' Banana ', ' eat ')
' Little turtle eats bananas '
>>> myfunc(' Banana ', ' eat ', ' monkey ')
' Monkeys eat bananas '
>> def myfunc(s=' Apple ', vt, o=' Little turtle '):
return ''.join((o, vt, s))
SyntaxError: non-default argument follows default argument // The default parameter should be placed at the end
>>> def myfunc(vt, s=' Apple ', o=' Little turtle '):
return ''.join((o, vt, s))
>>> myfunc(' Arched ')
' The little turtle arched the apple '
Cold knowledge :/ and *
The parameter to the left of the slash must be a positional parameter , It cannot be a keyword parameter .
To the left of the asterisk can be either a position parameter , It can also be a keyword parameter , The right side must be a keyword parameter .