经常看到很多函数里使用了 *args**kwargs,示例如:

function(params, *args, **kwargs)

而,该函数如何使用呢,参数如何通过 args 和 kwargs 进行传递的呢?

Understanding args & *kwargs in Python

1. 函数一般形式

首先,定义如下打印名字的函数:

def characters(name1, name2, name3):
    print(name1, name2, name3)

运行函数:

#
characters("Iron Man", "Black Panther", "Captain America")
#输出:
#Iron Man Black Panther Captain America

其中,name1、name2、name3 分别对应 Iron Man,Black Panther, Captain America.

再次运行函数:

characters("Iron Man", "Black Panther", "Captain America", "Hulk")
#出现报错:
#TypeError: characters() takes 3 positional arguments but 4 were given

此时,对于函数输入超过明确定义的变量的,则函数就会报错.

2. 使用 *args

*args 适用于函数传递的参数数量未知的场景.

其中,args 前的*确保了参数具有可变长度.

示例如,定义函数:

def friends(*args):
    print(args)

运行函数:

friends("Sachin", "Rishu", "Yashwant", "Abhishek")
#输出:
#('Sachin', 'Rishu', 'Yashwant', 'Abhishek')

其中,args是元组tuple形式.

再者,示例函数如:

def friends(greet, *args):
    for friend in args:
        print(f"{greet} to Python, {friend}")

运行函数:

greet = "Welcome"
friends(greet, "Sachin", "Rishu", "Yashwant", "Abhishek")
#输出:
'''
Welcome to Python, Sachin
Welcome to Python, Rishu
Welcome to Python, Yashwant
Welcome to Python, Abhishek
'''

实际上可以将 args 替换为任何其他名字,如:

def heroes(country, *characters):
    for character in characters:
        print(f"{character} is from {country}.")

3. 使用 **kwargs

kwargs 是 keyword argument 的缩写.

*kwargs 类似于 args. 不同之处在与,kwargs 是包含 keyword 或 named 参数. 其是 dict 形式,以 key-value 参数传递.

示例函数如:

def hello(**kwargs):
    print(type(kwargs))
    for key, value in kwargs.items():
        print(f"{key} is {value}.")

运行函数:

hello(One = "Red", two = "Green", three = "Blue")
#输出:
'''
<class 'dict'>
One is Red.
two is Green.
three is Blue.
'''

kwargs 也可以替换为其他字符,如:

def hello(write, **color):
    print(write)
    for key, value in color.items():
        print(f"{key} is {value}.")

4. 同时使用 args 和 *kwargs

如:

function(params, *args, **kwargs)

注:args 只能在 kwargs 前面.

示例函数如:

def friends(greet, *args, **kwargs):
    for names in args:
        print(f"{greet} to the Programming zone {names}")
    print("\nI am Veronica and I would like to announce your roles:")
    for key, value in kwargs.items():
        print(f"{key} is a {value}")

运行函数:

greet = "Welcome"
names = ["Sachin", "Rishu", "Yashwant", "Abhishek"]
roles = {"Sachin":"Chief Instructor", "Rishu":"Engineer",
         "Yashwant":"Lab Technician", "Abhishek":"Marketing Manager"}

friends(greet, *names, **roles)
#输出:
'''
Welcome to the Programming zone Sachin
Welcome to the Programming zone Rishu
Welcome to the Programming zone Yashwant
Welcome to the Programming zone Abhishek

I am Veronica and I would like to announce your roles:
Sachin is a Chief Instructor
Rishu is a Engineer
Yashwant is a Lab Technician
Abhishek is a Marketing Manager
'''

5. Unpacking Operator

单个 * 用于 unpack iterable;

两个 * 用于 unpack dict.

https://www.python.org/dev/peps/pep-0448/

Last modification:July 31st, 2022 at 11:08 pm