广受好评的Django教程现已更新至3.1版本,进行了全面细致的修订,添加了重要内容,更深入更丰富,恳请大家继续支持,衷心感谢!


user_image
By  夏目要坚强    On   2019年5月28日 08:46

传递实参的原则: * 位置实参必须在关键字实参的前面。 * 位置实参到形参的传递,按照从左到右的顺序,依次传递。 * 已经被位置实参赋值的形参,不可以再次使用关键字实参进行赋值,否则会报错。 * 调用函数时,传递的关键字参数会转化为位置参数,然后通过形参名称,实现形参(名称)与实参(对象)的绑定。参考:If keyword arguments are present, they are first converted to positional arguments, as follows. First, a list of unfilled slots is created for the formal parameters. If there are N positional arguments, they are placed in the first N slots. Next, for each keyword argument, the identifier is used to determine the corresponding slot (if the identifier is the same as the first formal parameter name, the first slot is used, and so on). If the slot is already filled, a TypeError exception is raised. Otherwise, the value of the argument is placed in the slot, filling it (even if the expression is None, it fills the slot). When all arguments have been processed, the slots that are still unfilled are filled with the corresponding default value from the function definition. (Default values are calculated, once, when the function is defined; thus, a mutable object such as a list or dictionary used as default value will be shared by all calls that don’t specify an argument value for the corresponding slot; this should usually be avoided.) If there are any unfilled slots for which no default value is specified, a TypeError exception is raised. Otherwise, the list of filled slots is used as the argument list for the call. * 传递的实参数目一定要与定义的形参数目匹配。 * 不匹配情况之一:某些形参被给与默认值,传入的参数的数目可以小于形参。 * 不匹配情况之二:有可以接受任意个数的形参,比如*parameter或者**paramater(本质上也算是匹配) * 总之:在函数调用时,形参一定要被传参,不管是来自于 位置实参,关键字实参还是默认值。参考:A function call always assigns values to all parameters mentioned in the parameter list, either from position arguments, from keyword arguments, or from default values.