Menu
CoddyTech

**kwarg 参数

本课属于 Coddy Python 学习旅程的“面向对象编程”单元。第 43 课,共 64 课。

**kwargs 是“关键字参数”的缩写。它允许函数接受任意数量的带名称的参数(例如 key=value 键值对),而无需提前定义所有参数。

工作原理:

  • *args → 将额外的位置参数收集到一个元组中
  • **kwargs → 将额外的关键字参数收集到一个字典中

简单示例

我们从最简单的例子开始:

def greet(**kwargs):
    print(kwargs)

greet(name="Alice", age=25, country="Australia")

输出:

{'name': 'Alice', 'age': 25, 'country': 'Australia'}

如你所见,**kwargs 会自动将所有关键字参数收集到一个字典中。

使用字典

由于 kwargs 已经是一个字典,你可以直接遍历它:

def print_info(**kwargs):
    print("Information received:")
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Bob", age=30, job="Teacher")

输出:

Information received:
name: Bob
age: 30
job: Teacher

将常规参数与 **kwargs 混合使用

你可以将常规参数与 **kwargs 结合使用:

def create_profile(name, **details):
    print(f"Creating profile for: {name}")
    print("Additional details:")
    for key, value in details.items():
        print(f"  {key}: {value}")

create_profile("Sarah", age=28, city="London", hobby="Reading")

输出:

Creating profile for: Sarah
Additional details:
  age: 28
  city: London
  hobby: Reading

空的 **kwargs

如果没有传入关键字参数,kwargs 将是一个空字典:

def show_data(**kwargs):
    if kwargs:
        print("Data:", kwargs)
    else:
        print("No data provided")

show_data()  # 不传参数
show_data(item="apple")  # 传入参数

输出:

No data provided
Data: {'item': 'apple'}

现实示例:使用 **kwargs 的类

下面介绍如何在类中使用 **kwargs:

class Person:
    def __init__(self, name, **kwargs):
        self.name = name
        self.details = kwargs
    
    def show_info(self):
        print(f"Name: {self.name}")
        for key, value in self.details.items():
            print(f"{key}: {value}")

person = Person("Alice", age=25, city="New York", job="Engineer")
person.show_info()

输出:

Name: Alice
age: 25
city: New York
job: Engineer

解包字典

调用函数时,你也可以解包字典:

def display_settings(**kwargs):
    for setting, value in kwargs.items():
        print(f"{setting} = {value}")

settings = {"debug": True, "verbose": False, "timeout": 30}
display_settings(**settings)  # 解包字典

输出:

debug = True
verbose = False
timeout = 30

要点:

  • **kwargs 会将关键字参数收集到一个字典中:不需要转换,它本身已经是字典
  • kwargs 是约定俗成的名称,** 后面可以使用任何名称
  • 需要灵活的函数签名时,可以使用它
  • 它非常适合处理可选参数或配置设置
challenge icon

挑战

简单

在这个挑战中,你将实现一个人员创建系统,并为它编写全面的测试。

你只需要编辑 仅 person_creator.py 文件,并按照 TODO 注释的指引完成实现。该文件包含用于创建和管理具有各种属性的人员对象的类结构。

亲手试试

from person_creator import create_person

# 综合测试用例处理程序
test_case = input()

if test_case == "basic_test":
    create_person(name="John", age=25, occupation="Engineer")
    # 输出:
    # Person created with properties:
    # name: John
    # age: 25
    # occupation: Engineer

elif test_case == "empty_test":
    create_person()
    # 输出:
    # Person created with properties:
    # (没有属性,因此没有其他输出)

elif test_case == "many_properties":
    create_person(name="Alice", age=30, occupation="Doctor", city="New York", 
                 country="USA", hobby="Reading", email="alice@example.com")
    # 输出:
    # Person created with properties:
    # name: Alice
    # age: 30
    # occupation: Doctor
    # city: New York
    # country: USA
    # hobby: Reading
    # email: alice@example.com

elif test_case == "special_characters":
    create_person(name="Bob", email="bob@example.com", phone="123-456-7890")
    # 输出:
    # Person created with properties:
    # name: Bob
    # email: bob@example.com
    # phone: 123-456-7890

elif test_case == "numeric_keys":
    create_person(name="Charlie", age=35, height=175, weight=70)
    # 输出:
    # Person created with properties:
    # name: Charlie
    # age: 35
    # height: 175
    # weight: 70

elif test_case == "boolean_values":
    create_person(name="David", is_student=True, is_employed=False)
    # 输出:
    # Person created with properties:
    # name: David
    # is_student: True
    # is_employed: False

elif test_case == "nested_structures":
    create_person(name="Eve", hobbies=["Reading", "Swimming", "Coding"], 
                 address={"city": "Boston", "state": "MA", "zip": "02108"})
    # 输出:
    # Person created with properties:
    # name: Eve
    # hobbies: ['Reading', 'Swimming', 'Coding']
    # address: {'city': 'Boston', 'state': 'MA', 'zip': '02108'}

elif test_case == "unicode_characters":
    create_person(name="José", city="São Paulo", country="Brasil")
    # 输出:
    # Person created with properties:
    # name: José
    # city: São Paulo
    # country: Brasil
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向对象编程中的所有课

自己练习: Python 在线编译器