第407页 | Learning Python | 阅读 ‧ 电子书库

同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库

The Gritty Details

If you choose to use and combine the special argument-matching modes, Python will ask you to follow these ordering rules:

 

 
In a function call, arguments must appear in this order: any positional arguments (value), followed by a combination of any keyword arguments (name=value) and the *sequence form, followed by the **dict form. In a function header, arguments must appear in this order: any normal arguments (name), followed by any default arguments (name=value), followed by the *name (or * in 3.0) form if present, followed by any name or name=value keyword-only arguments (in 3.0), followed by the **name form.

In both the call and header, the **arg form must appear last if present. If you mix arguments in any other order, you will get a syntax error because the combinations can be ambiguous. The steps that Python internally carries out to match arguments before assignment can roughly be described as follows:

 

 
Assign nonkeyword arguments by position.Assign keyword arguments by matching names.Assign extra nonkeyword arguments to *name tuple. Assign extra keyword arguments to **name dictionary. Assign default values to unassigned arguments in header.

After this, Python checks to make sure each argument is passed just one value; if not, an error is raised. When all matching is complete, Python assigns argument names to the objects passed to them.

The actual matching algorithm Python uses is a bit more complex (it must also account for keyword-only arguments in 3.0, for instance), so we’ll defer to Python’s standard language manual for a more exact description. It’s not required reading, but tracing Python’s matching algorithm may help you to understand some convoluted cases, especially when modes are mixed.

Note

In Python 3.0, argument names in a function header can also have annotation values, specified as name:value (or name:value=default when defaults are present). This is simply additional syntax for arguments and does not augment or change the argument-ordering rules described here. The function itself can also have an annotation value, given as def f()->value. See the discussion of function annotation in Chapter 19 for more details.

请支持我们,让我们可以支付服务器费用。
使用微信支付打赏


上一页 · 目录下一页


下载 · 书页 · 阅读 ‧ 电子书库