python not accept keyword arguments

前端 未结 5 1046
萌比男神i
萌比男神i 2021-01-12 08:13

I am trying to make my code NOT to accept keyword arguments just like some bulitins also do not accept keyword arguments, but, I am unable to do so. Here, is my thinking acc

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-12 08:37

    Looking at the function call somefunc(b=10,a=20) and not the function definition, this can seem to be either of a call to a function which accepts just normal arguments or a function which accepts keyword arguments. How does the interpreter differentiate between the two?

    Not sure if this is quite what you're asking, but if I understand you right, the answer is "it doesn't". You can call the function with keywords no matter how the arguments are defined in the function. If you pass any arguments using keyword syntax (e.g., f(a=...)), Python binds the corresponding values to the arguments with the same names in the function definition. It doesn't matter whether a default value was defined. The two kinds of function definition don't create different "kinds" of arguments, it's just that some of the arguments might have default values and others might not. So whether you do def f(a) or def f(a=2), you can still do f(a=...). The only restriction is that you have to pass/define positional arguments first (e.g., you can't do def f(a=2, b) or f(a=2, 3)). See also this answer.

    As for the second part of your question, I'm not aware of any way to stop a Python function from accepting keyword-passed values for named arguments. If you define only *args then it won't accept keyword arguments, but the positional arguments can't have separate names.

提交回复
热议问题