Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 使用位置参数和关键字参数的顺序_Python 3.x_Function_Keyword Argument_Positional Parameter - Fatal编程技术网

Python 3.x 使用位置参数和关键字参数的顺序

Python 3.x 使用位置参数和关键字参数的顺序,python-3.x,function,keyword-argument,positional-parameter,Python 3.x,Function,Keyword Argument,Positional Parameter,显然,如果在调用函数时需要同时使用关键字参数和位置参数,则必须首先使用位置参数。但是下面的代码会导致错误 def greet(first_name, l_name): print(f'Hi, {first_name} {last_name}!') greet('Holmes', first_name='Harry') 那么这是否意味着如果同时使用这两个参数,则必须先按要求的顺序使用位置参数,然后才使用关键字参数?位置参数必须按函数中声明的顺序传递。因此,如果传递三个位置参数,它们必须转

显然,如果在调用函数时需要同时使用关键字参数和位置参数,则必须首先使用位置参数。但是下面的代码会导致错误

def greet(first_name, l_name):
   print(f'Hi, {first_name} {last_name}!')

greet('Holmes',
first_name='Harry')

那么这是否意味着如果同时使用这两个参数,则必须先按要求的顺序使用位置参数,然后才使用关键字参数?

位置参数必须按函数中声明的顺序传递。因此,如果传递三个位置参数,它们必须转到函数的前三个参数,而这三个参数不能通过关键字传递。如果希望能够按关键字顺序传递第一个参数,则所有参数都必须按关键字传递(如果它们具有默认值,则根本不传递)

如果有帮助,Python的绑定机制大致如下:

  • 将位置参数逐个指定给函数的顺序参数。这些参数现在已设置
  • 将关键字参数按任意顺序分配给其余参数。如果其中一个关键字参数与已按位置分配的参数匹配(或同一关键字参数被传递两次),则为错误
  • 就您而言,这意味着:

    greet('Holmes', first_name='Harry')
    
    first将
    'Holmes'
    绑定到
    first\u name
    。然后它看到您试图再次将
    first_name
    作为关键字参数传递,并被拒绝