Normal arguments vs. keyword arguments

后端 未结 10 918
一个人的身影
一个人的身影 2020-11-22 02:35

How are \"keyword arguments\" different from regular arguments? Can\'t all arguments be passed as name=value instead of using positional syntax?

10条回答
  •  天命终不由人
    2020-11-22 02:55

    There is one last language feature where the distinction is important. Consider the following function:

    def foo(*positional, **keywords):
        print "Positional:", positional
        print "Keywords:", keywords
    

    The *positional argument will store all of the positional arguments passed to foo(), with no limit to how many you can provide.

    >>> foo('one', 'two', 'three')
    Positional: ('one', 'two', 'three')
    Keywords: {}
    

    The **keywords argument will store any keyword arguments:

    >>> foo(a='one', b='two', c='three')
    Positional: ()
    Keywords: {'a': 'one', 'c': 'three', 'b': 'two'}
    

    And of course, you can use both at the same time:

    >>> foo('one','two',c='three',d='four')
    Positional: ('one', 'two')
    Keywords: {'c': 'three', 'd': 'four'}
    

    These features are rarely used, but occasionally they are very useful, and it's important to know which arguments are positional or keywords.

提交回复
热议问题