Normal arguments vs. keyword arguments

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

提交回复
热议问题