预计阅读本页时间:-
The Basics
Before we go into the syntactic details, I want to stress that these special modes are optional and only have to do with matching objects to names; the underlying passing mechanism after the matching takes place is still assignment. In fact, some of these tools are intended more for people writing libraries than for application developers. But because you may stumble across these modes even if you don’t code them yourself, here’s a synopsis of the available tools:
Positionals: matched from left to right
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
The normal case, which we’ve mostly been using so far, is to match passed argument values to argument names in a function header by position, from left to right.
Keywords: matched by argument name
Alternatively, callers can specify which argument in the function is to receive a value by using the argument’s name in the call, with the name=value syntax.
Defaults: specify values for arguments that aren’t passed
Functions themselves can specify default values for arguments to receive if the call passes too few values, again using the name=value syntax.
Varargs collecting: collect arbitrarily many positional or keyword arguments
Functions can use special arguments preceded with one or two * characters to collect an arbitrary number of extra arguments (this feature is often referred to as varargs, after the varargs feature in the C language, which also supports variable-length argument lists).
Varargs unpacking: pass arbitrarily many positional or keyword arguments
Callers can also use the * syntax to unpack argument collections into discrete, separate arguments. This is the inverse of a * in a function header—in the header it means collect arbitrarily many arguments, while in the call it means pass arbitrarily many arguments.
Keyword-only arguments: arguments that must be passed by name
In Python 3.0 (but not 2.6), functions can also specify arguments that must be passed by name with keyword arguments, not by position. Such arguments are typically used to define configuration options in addition to actual arguments.