gpt4 book ai didi

python - *(单星)和/(斜线)作为独立参数有什么作用?

转载 作者:行者123 更新时间:2023-12-01 07:18:02 27 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Bare asterisk in function arguments?

(6 个回答)



What does the slash mean in help() output?

(3 个回答)


2年前关闭。




在下面的函数定义中, 的作用是什么? * /占?

def func(self, param1, param2, /, param3, *, param4, param5):
print(param1, param2, param3, param4, param5)

注意:不要误认为 *args | 中的单|双星号。 **kwargs ( solved here)

最佳答案

有一个new function parameter syntax /表示某些函数参数必须按位置指定,不能用作关键字参数。[ 这是 Python 3.8 中的新功能 ]
文档详细说明了 positional-only parameters 的一些用例/好处。

  1. It allows pure Python functions to fully emulate behaviors ofexisting C coded functions. For example, the built-in pow()function does not accept keyword arguments:

    def pow(x, y, z=None, /):
    "Emulate the built in pow() function"
    r = x ** y
    return r if z is None else r%z
  2. Another use case is to preclude keyword arguments when the parametername is not helpful. For example, the builtin len() function hasthe signature len(obj, /). This precludes awkward calls such as:

    len(obj='hello')  # The "obj" keyword argument impairs readability
  3. A further benefit of marking a parameter as positional-only is thatit allows the parameter name to be changed in the future withoutrisk of breaking client code. For example, in the statistics module,the parameter name dist may be changed in the future. This was madepossible with the following function specification:

    def quantiles(dist, /, *, n=4, method='exclusive')
    ...

其中 *用于强制 caller to use named arguments . This is命名参数的用例之一。
所以,给定方法,
def func(self, param1, param2, /, param3, *, param4, param5):
print(param1, param2, param3, param4, param5)
它必须调用
obj.func(10, 20, 30, param4=50, param5=60)
或者
obj.func(10, 20, param3=30, param4=50, param5=60)
IE,
  • param1 , param2必须指定 positionally .
  • param3可以通过 positional 调用或 keyword .
  • param4param5必须用 keyword 调用争论。

  • 演示:
    >>> class MyClass(object):
    ... def func(self, param1, param2, /, param3, *, param4, param5):
    ... return param1, param2, param3, param4, param5
    ...
    >>> obj = MyClass()
    >>>
    >>> assert obj.func(10, 20, 30, param4=40, param5=50), obj.func(
    ... 10, 20, param3=30, param4=40, param5=50
    ... )

    关于python - *(单星)和/(斜线)作为独立参数有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59661042/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com