默认参数后跟可变长度参数(Python)

时间:2017-11-14 16:59:44

标签: python python-3.x python-2.7 arguments parameter-passing

我有一个函数,它接受一个位置参数,一个默认参数,可变长度非关键字参数和可变长度关键字参数。该功能如下所示:

def set_football_team(name,
                     coach = '',
                     *players, **formations):
    print("Team: "+name)
    print("Coach: "+coach)
    for i, player in enumerate(players):
        print("Player "+str(i+1)+": "+player)
    for position, positional_players in formations.items():
        positional_players = ", ".join(positional_players)
        print(position+": "+positional_players)

传递所有参数时工作正常。

name = "Real Madrid"
coach = "Zinedine Zidane"
players = ["Keylor Navas", "K. Casilla",
           "Sergio Ramos", "Varane", "Marcelo"]

formations = {"Goalkeeper": players[:2],
              "Defender": players[2:]}

set_football_team(name, coach, *players, **formations)

Output
==============================================
Team: Real Madrid
Coach: Zinedine  Zidane
Player 1: Keylor Navas
Player 2: K. Casilla
Player 3: Sergio Ramos
Player 4: Varane
Player 5: Marcelo
Goalkeeper: Keylor Navas, K. Casilla
Defender: Sergio Ramos, Varane, Marcelo

但是当我跳过传递coach时,即使我将coach设置为参数中的空字符串,它也会显示意外输出:

name = "Real Madrid"
players = ["Keylor Navas", "K. Casilla",
           "Sergio Ramos", "Varane", "Marcelo"]

formations = {"Goalkeeper": players[:2],
              "Defender": players[2:]}

set_football_team(name, *players, **formations)

Output
==============================================    
Team: Real Madrid
Coach: Keylor Navas
Player 1: K. Casilla
Player 2: Sergio Ramos
Player 3: Varane
Player 4: Marcelo
Goalkeeper: Keylor Navas, K. Casilla
Defender: Sergio Ramos, Varane, Marcelo

我知道函数参数的顺序:

positional argument > default argument > variable length non keyword arguments > variable length keyword arguments

上述行为的原因是什么?我错过了什么?

我该如何克服这个问题?

1 个答案:

答案 0 :(得分:1)

set_football_team(name, coach, *players, **formations)

如上所述调用函数时,如果将coach作为参数传递,则会为coach分配在函数set_football_team的参数中传递的值。

set_football_team(name,*players, **formations)

当没有明确传递coach参数时如上所述调用该函数时,coach主要被赋予*玩家的第一个值,玩家的剩余值被传递给玩家,这就是为什么你只注意到4个玩家的玩家而列表中的第0个元素已分配给coach。