gpt4 book ai didi

python - 只允许名称参数的函数

转载 作者:太空狗 更新时间:2023-10-30 00:27:48 26 4
gpt4 key购买 nike

我在 Python Cookbooks 中阅读了一个解决方案,用于创建一个只允许名称参数的函数。我编写了自己的代码来尝试一下:

class Reporter(object):
def __init__(self, *, testline=None, sw_ver= None, directory=None):
pass

if __name__ == "__main__"
r = Reporter()

但是解释器显示此错误:

File "Reporter.py", line 6
def __init__(self, *, testline=None, sw_ver= None, directory=None):
^
SyntaxError: invalid syntax

为什么会显示这个?

最佳答案

您使用的代码有效语法,但对于python3,所以本书必须使用python3 语法,它只允许关键字参数,pep-3102 :

python 3 new syntax

You can also use a bare * in the parameter list to indicate that you don’t accept a variable-length argument list, but you do have keyword-only arguments.

使用您的代码并在 python 3 中传递非关键字会出错,但原因不同:

TypeError                                 Traceback (most recent call last)
<ipython-input-2-b4df44fa1e0c> in <module>()
1 if __name__ == "__main__":
----> 2 r = Reporter(4)
3

TypeError: __init__() takes 1 positional argument but 2 were given

一旦你使用关键字,它就可以正常工作:

In [4]: if __name__ == "__main__":
r = Reporter(testline=4)
...:

使用具有相同语法的函数可能会产生更明显的错误:

def f(*, foo=None, bar=None):
return foo, bar


In [6]: f(4)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-a122d87dbe99> in <module>()
----> 1 f(4)

TypeError: f() takes 0 positional arguments but 1 was given

如果你想允许一些位置参数并且有可选的关键字参数传递但仅按名称传递,它也很有用:

def f(a,b, *, foo=None, bar=None):
return a, b, foo, bar

然后传递 3 个位置参数会出错:

In [8]: f(1,2,3)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-b61741968103> in <module>()
----> 1 f(1,2,3)

TypeError: f() takes 2 positional arguments but 3 were given

关于python - 只允许名称参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31939890/

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