Python函数定义中的正斜杠? [英] Bare forward slash in Python function definition?

查看:498
本文介绍了Python函数定义中的正斜杠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

In the Python 3.8 Programming FAQ, I saw the following function definition:

class callByRef:
    def __init__(self, /, **args):
        for key, value in args.items():
            setattr(self, key, value)

Python 3.7版本:

class callByRef:
    def __init__(self, **args):
        for (key, value) in args.items():
            setattr(self, key, value)

这种新的/语法是什么?

它与出现在help()输出中的/有什么关系?

How does it relate to a / appearing in help() output?

注意:

Note: this and this question are about help() annotation, whereas this question is about new syntax and any differences to the help() annotation.

推荐答案

语法简介

/作为语法是 Python 3.8中引入的.

参数列表中/的基本原理在 PEP 570中给出- -Python仅位置参数:

The rationale for / in an argument list is given in PEP 570 -- Python Positional-Only Parameters:

新语法将使库作者可以进一步控制如何调用其API.它将允许指定哪些参数必须称为仅位置参数,同时防止将它们称为关键字参数.

The new syntax will enable library authors to further control how their API can be called. It will allow designating which parameters must be called as positional-only, while preventing them from being called as keyword arguments.

以前,(信息性的) PEP 457 定义了语法,但是范围更模糊.该PEP通过证明语法并为函数定义中的/语法提供实现,使原始建议更进一步.

Previously, (informational) PEP 457 defined the syntax, but with a much more vague scope. This PEP takes the original proposal a step further by justifying the syntax and providing an implementation for the / syntax in function definitions.

语法和注释性PEP的比较

相似之处

出于所有意图和目的,如果您理解help()/表示法,则这就是通过PEP 570在v3.8中正式包含为Python语法的内容.

For all intents and purposes, if you understand help()'s / notation, then that's what is formally included as Python syntax in v3.8 via PEP 570.

差异

  • PEP 570 -- Python Positional-Only Parameters

  • 定义Python 3.8+的语法
  • 语法的正式语法规范
  • 类型:已接受

PEP 457 -- Notation For Positional-Only Parameters

  • 定义在help()批注中使用的表示法(不是语法)
  • 非正式的英语描述
  • 类型:信息性
  • Defines notation (not syntax) used in help() annotations
  • Informal English language description
  • Type: Informational

对于参数中/的含义和用法,已经有了很好的答案.

There are already excellent answers on the meaning and usage of / in arguments.

要为您节省点击次数:

A /表示所有之前的参数都是仅位置参数.调用函数时,不能将/ 之前的仅位置参数作为name=value传递.

A / means that all preceding parameters are positional-only parameters. Positional-only parameters before a / cannot be passed as name=value when calling the function.

Python 3.8新增功能给出了以下示例:

def pow(x, y, z=None, /):
    r = x**y
    if z is not None:
        r %= z
    return r

有效函数调用:

  • pow(2, 10)
  • pow(2, 10, 17)
  • pow(2, 10)
  • pow(2, 10, 17)

无效函数调用:

  • pow(x=2, y=10)
  • pow(2, 10, z=17)
  • pow(x=2, y=10)
  • pow(2, 10, z=17)

这篇关于Python函数定义中的正斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆