我是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