Eri*_*ric 204 python parameter-passing python-3.x
函数参数中的星号是什么?
当我查看pickle模块时,我看到了这一点:(http://docs.python.org/3.3/library/pickle.html#pickle.dump)
pickle.dump(obj, file, protocol=None, *, fix_imports=True)
Run Code Online (Sandbox Code Playgroud)
我知道在参数之前的单个和双星号(对于可变数量的参数),但这没有任何结果.而且我很确定这与泡菜无关.这可能就是这种情况的一个例子.我把它发送给翻译时我才知道它的名字:
>>> def func(*):
... pass
...
File "<stdin>", line 1
SyntaxError: named arguments must follow bare *
Run Code Online (Sandbox Code Playgroud)
如果重要的话,我在python 3.3.0上.
Kim*_*ais 192
Bare *
用于强制调用者使用命名参数 - 因此*
当您没有以下关键字参数时,不能将函数定义为参数.
有关更多详细信息,请参阅此答案或Python 3文档.
mu *_*u 無 62
虽然原始答案完全回答了问题,但只需添加一些相关信息.单个星号的行为来自PEP-3102
.引用相关部分:
The second syntactical change is to allow the argument name to
be omitted for a varargs argument. The meaning of this is to
allow for keyword-only arguments for functions that would not
otherwise take a varargs argument:
def compare(a, b, *, key=None):
...
Run Code Online (Sandbox Code Playgroud)
简单来说,这意味着要传递key的值,您需要明确地传递它key="value"
.
kay*_*ya3 17
从语义上讲,这意味着它后面的参数只有关键字,所以如果你试图提供一个参数而不指定它的名字,你会得到一个错误。例如:
>>> def f(a, *, b):
... return a + b
...
>>> f(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() takes 1 positional argument but 2 were given
>>> f(1, b=2)
3
Run Code Online (Sandbox Code Playgroud)
实际上,这意味着您必须使用关键字参数调用该函数。如果没有参数名称给出的提示,很难理解参数的目的,通常会这样做。
比较例如sorted(nums, reverse=True)
与如果你写的sorted(nums, True)
。后者的可读性要差得多,因此 Python 开发人员选择让您以前者的方式编写它。
rok*_*rok 12
假设你有函数:
def sum(a,key=5):
return a + key
Run Code Online (Sandbox Code Playgroud)
您可以通过两种方式调用此函数:
sum(1,2)
或者 sum(1,key=2)
假设您希望sum
仅使用关键字参数调用函数。
您添加*
到函数参数列表以标记位置参数的结尾。
所以函数定义为:
def sum(a,*,key=5):
return a + key
Run Code Online (Sandbox Code Playgroud)
只能使用 sum(1,key=2)
lay*_*cat 11
def func(*, a, b):
print(a)
print(b)
func("gg") # TypeError: func() takes 0 positional arguments but 1 was given
func(a="gg") # TypeError: func() missing 1 required keyword-only argument: 'b'
func(a="aa", b="bb", c="cc") # TypeError: func() got an unexpected keyword argument 'c'
func(a="aa", b="bb", "cc") # SyntaxError: positional argument follows keyword argument
func(a="aa", b="bb") # aa, bb
Run Code Online (Sandbox Code Playgroud)
上面带有** kwargs的示例
def func(*, a, b, **kwargs):
print(a)
print(b)
print(kwargs)
func(a="aa",b="bb", c="cc") # aa, bb, {'c': 'cc'}
Run Code Online (Sandbox Code Playgroud)