代码之家  ›  专栏  ›  技术社区  ›  Shiv Deepak

以星号和双星号开头的python方法/函数参数[重复]

  •  82
  • Shiv Deepak  · 技术社区  · 15 年前

    我无法理解这些类型的函数在哪里使用,以及这些参数与正常参数的工作方式有多不同。我见过他们很多次,但从来没有机会正确理解他们。

    前任:

    def method(self, *links, **locks):
        #some foo
        #some bar
        return
    

    我知道我可以搜索文档,但我不知道要搜索什么。

    1 回复  |  直到 8 年前
        1
  •  122
  •   0 _ Edward Ned Harvey    8 年前

    这个 *args **keywordargs 表单分别用于传递参数列表和参数字典。所以如果我有这样的功能:

    def printlist(*args):
        for x in args:
            print(x)
    

    我可以这样称呼它:

    printlist(1, 2, 3, 4, 5)  # or as many more arguments as I'd like
    

    为此

    def printdict(**kwargs):
        print(repr(kwargs))
    
    printdict(john=10, jill=12, david=15)
    

    *精氨酸 行为就像一个列表,并且 **键盘 行为类似于字典,但不必显式地传递 list 或A dict 到函数。

    this 更多示例。