python - 函数中的 Kwargs
问题描述
我是 Python 新手,刚刚了解了 **kwargs。
def myfunc(**kwargs):
if 'fruit' in kwargs:
print(f'My fruit of choice is {kwargs["fruit"]}')
else:
print('I did not find any fruit here')
myfunc(fruit='apple')
调用函数时,为什么关键字fruit没有在引号中?
为什么与此不同:
d = {'one':1}
d['one']
提前致谢。
解决方案
简短的回答是“这就是它的工作原理”。
更长的答案:
在函数调用的上下文中,参数名称不是str
对象,也不是任何其他类型的对象或表达式;他们只是名字。它们没有引号,因为它们不是字符串文字表达式。
换句话说,你不能这样做:
>>> myfunc('fruit'='apple')
File "<stdin>", line 1
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
你也不能:
>>> argname = 'fruit'
>>> myfunc(argname='apple') # argname does not evaluate to 'fruit'!
I did not find any fruit here
在您的字典查找示例中,您可以使用任何类型的表达式作为字典键:
>>> d['o'+'n'+'e']
1
>>> one = 'one'
>>> d[one]
1
因此,如果您希望键是字符串文字,则需要在其周围加上引号。
**kwargs
如果您在函数定义中实际命名参数而不是使用接受任意参数,则命名参数语法更容易理解 IMO :
def myfunc(fruit=None):
if fruit is not None:
print(f'My fruit of choice is {fruit}')
else:
print('I did not find any fruit here')
这样,函数定义中的语法与调用者中的语法看起来相同(fruit
是名称,而不是字符串文字'fruit'
)。
请注意,您可以使用**
相反的语法来传递命名参数的字典;在这种情况下,字典是正常定义的,str
键可以是字符串文字或其他str
表达式:
>>> myfunc(fruit='apple')
My fruit of choice is apple
>>> myfunc(**{'fruit': 'apple'})
My fruit of choice is apple
>>> k = 'fruit'
>>> v = 'apple'
>>> myfunc(**{k: v})
My fruit of choice is apple