当使用** kwargs时,字典的语法如何变化(因为显然键必须是字符串)?

例如,在这段代码中,键似乎是使用'='符号的关键字,而不是第二段代码中通常的dict语法{“ key”:“ value”}

    def myfunc(**kwargs):
        if "fruits" in kwargs:
            print(f"My fruit of choice is {kwargs['fruits']}")
        else:
            print("I did not find any fruit here")
    myfunc(fruits = "apple", veggies = "cabbage")



    my_dict = {"fruits":"apple", "veggies":"cabbages"}
    my_dict["fruits"]
评论
  • 思雁
    思雁 回复

    关键字参数要早于指定任意关键字参数的能力。最初,只有位置参数:

    def foo(a, b):
        ...
    

    并且您只能指定位置参数:

    foo(3, 5)
    

    接下来是关键字参数:您可以在调用时按名称指定参数,以提高可读性并放宽按定义顺序提供参数的要求:

    foo(a=3, b=5)
    foo(b=5, a=3)  # Identical to the above
    

    Later, the ability to add keyword arguments that weren't predefined as parameters was added. These are exposed inside the function as a dict, created at call time, and assigned to the parameter prefixed with **:

    def foo(a, b, **kwargs):
        ...
    
    foo(a=3, b=5, c=9)  # kwargs['c'] will have the value 9.
    

    No change was made to the calling syntax; as far as the caller is concerned, the fact that a dict is used to access the value of c is an implementation detail, and one that is not exposed outside the function.

    A separate, but related, use of ** is to unpack a dict as a sequence of keyword arguments:

    foo(**{'a': 3, 'b': 5})  # Equivalent to foo(a=3, b=5)