繁体   English   中英

函数中的 Kwargs

[英]Kwargs in a function

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM