我对这个说法感到困惑 "print(kw,":",keywords[kw])" 在下面的程序中,在python中。

def cheeseshop(kind,*arguments,**keywords):
    print("--Do you have any",kind,"?")
    print("--I'm sorry, we're all out of",kind)
    for arg in arguments:
       print(arg)
    print("-"*40)
    print(keywords)
    keys=sorted(keywords)
    print(keys)
    for kw in keys:
        print(kw,":",keywords[kw])


cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper="Michael Palin",
           client="John Cleese",
           sketch="Cheese Shop Sketch")

结果如下:

--Do you have any Limburger ?
--I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
{'client': 'John Cleese', 'sketch': 'Cheese Shop Sketch', 'shopkeeper': 'Michael Palin'}
['client', 'shopkeeper', 'sketch']
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch

在我的想法中,"kw"应该是 "客户"、"素描"及"店主", 不是数字,那么"kw"怎么可能是语句中关键字的索引 "print(kw,":",keywords[kw])"?

为了验证我的想法,我还尝试了另一个程序:

letters=['a','b']
for kw in letters:
   print(letters[kw])

并弹出合理的回复:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: list indices must be integers, not str

这进一步混淆了我在第一部分程序中遇到的问题。我认为它应该弹出同样的错误给我。

有帮助吗?

解决方案

函数参数前面有 ** 被称为"关键字参数",在调用函数时采用命名参数,例如: client="John Cleese" 在你的例子中。在这种情况下,"client"是名称,"John Cleese"是值。通过这种方式传递的参数被放置在一个 dict, ,这是一个键值存储而不是列表,您可能在表单中熟悉它

x = {
      "foo": "bar"
    } 
print x["foo"] # prints "bar"

其他提示

它使用关键字实用程序,它是一个带有键名的数组。

你可以看到lib描述,在python文档中这里

事实上,有一个特殊属性的**关键字参数,提供了这样做的权利。

这里是一个使用它的教程(并且还要了解它)和这里是stackoverflow相关的问题。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top