*args and **kwargs?

小禾

来自: 小禾(焦点指向自我而非判断外界) 2013-11-07 10:52:20

×
加入小组后即可参加投票
  • 小禾

    小禾 (焦点指向自我而非判断外界) 2013-11-07 11:15:09

    Here's an example that uses 3 different types of parameters.

    def func(required_arg, *args, **kwargs):
    # required_arg is a positional-only parameter.
    print required_arg

    # args is a tuple of positional arguments,
    # because the parameter name has * prepended.
    if args: # If args is not empty.
    print args

    # kwargs is a dictionary of keyword arguments,
    # because the parameter name has ** prepended.
    if kwargs: # If kwargs is not empty.
    print kwargs

    >>> func()
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: func() takes at least 1 argument (0 given)

    >>> func("required argument")
    required argument

    >>> func("required argument", 1, 2, '3')
    required argument
    (1, 2, '3')

    >>> func("required argument", 1, 2, '3', keyword1=4, keyword2="foo")
    required argument
    (1, 2, '3')
    {'keyword2': 'foo', 'keyword1': 4}

你的回应

回应请先 , 或 注册

1 人聚集在这个小组
↑回顶部