代码之家  ›  专栏  ›  技术社区  ›  arshovon

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

  •  -1
  • arshovon  · 技术社区  · 7 年前

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

    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 它显示了意外的输出,即使我设置了 教练 到参数中的空字符串:

    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 回复  |  直到 3 年前
        1
  •  1
  •   dev2qa    7 年前
    set_football_team(name, coach, *players, **formations)
    

    如上所述调用函数时,coach作为参数传递,coach将被分配在函数set\u football\u team的参数中传递的值。

    set_football_team(name,*players, **formations)
    

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