Normal arguments vs. keyword arguments

后端 未结 10 751
一个人的身影
一个人的身影 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.

    0 讨论(0)
  • 2020-11-22 02:55

    I'm surprised no one has mentioned the fact that you can mix positional and keyword arguments to do sneaky things like this using *args and **kwargs (from this site):

    def test_var_kwargs(farg, **kwargs):
        print "formal arg:", farg
        for key in kwargs:
            print "another keyword arg: %s: %s" % (key, kwargs[key])
    

    This allows you to use arbitrary keyword arguments that may have keys you don't want to define upfront.

    0 讨论(0)
  • 2020-11-22 02:59

    Using keyword arguments is the same thing as normal arguments except order doesn't matter. For example the two functions calls below are the same:

    def foo(bar, baz):
        pass
    
    foo(1, 2)
    foo(baz=2, bar=1)
    
    0 讨论(0)
  • 2020-11-22 03:02

    Using Python 3 you can have both required and non-required keyword arguments:


    Optional: (default value defined for param 'b')

    def func1(a, *, b=42):
        ...
    func1(value_for_a) # b is optional and will default to 42
    

    Required (no default value defined for param 'b'):

    def func2(a, *, b):
        ... 
    func2(value_for_a, b=21) # b is set to 21 by the function call
    func2(value_for_a) # ERROR: missing 1 required keyword-only argument: 'b'`
    

    This can help in cases where you have many similar arguments next to each other especially if they are of the same type, in that case I prefer using named arguments or I create a custom class if arguments belong together.

    0 讨论(0)
提交回复
热议问题