Menu
CoddyTech

Tham số **kwarg

Thuộc phần Lập trình hướng đối tượng trong hành trình Python của Coddy. Bài học 43 trên 64.

**kwargs là cách viết tắt của “đối số từ khóa”. Nó cho phép một hàm nhận bất kỳ số lượng đối số có tên nào (như các cặp key=value) mà không cần định nghĩa trước tất cả.

Cách hoạt động:

  • *args → thu thập các đối số vị trí bổ sung vào một tuple
  • **kwargs → thu thập các đối số từ khóa bổ sung vào một từ điển

Ví dụ đơn giản

Hãy bắt đầu với ví dụ đơn giản nhất có thể:

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

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

Đầu ra:

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

Như bạn thấy, **kwargs tự động gom tất cả đối số từ khóa vào một từ điển.

Sử dụng từ điển

Vì kwargs đã là một từ điển, bạn có thể lặp trực tiếp qua nó:

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")

Đầu ra:

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

Kết hợp tham số thông thường với **kwargs

Bạn có thể kết hợp các tham số thông thường với **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")

Đầu ra:

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

**kwargs rỗng

Nếu không có đối số từ khóa nào được truyền vào, kwargs sẽ là một từ điển rỗng:

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

show_data()  # Không có đối số
show_data(item="apple")  # Có đối số

Đầu ra:

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

Ví dụ thực tế: lớp với **kwargs

Đây là cách bạn có thể dùng **kwargs trong một lớp:

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()

Đầu ra:

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

Giải nén từ điển

Bạn cũng có thể giải nén từ điển khi gọi hàm:

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

settings = {"debug": True, "verbose": False, "timeout": 30}
display_settings(**settings)  # Giải nén từ điển

Đầu ra:

debug = True
verbose = False
timeout = 30

Điểm chính:

  • **kwargs gom các đối số từ khóa vào một từ điển: không cần chuyển đổi vì nó đã là một từ điển
  • Tên kwargs là tên gọi theo quy ước, bạn có thể dùng bất kỳ tên nào sau **
  • Dùng nó khi bạn muốn chữ ký hàm linh hoạt
  • Rất hữu ích để xử lý các tham số tùy chọn hoặc cài đặt cấu hình
challenge icon

Thử thách

Dễ

Trong thử thách này, bạn sẽ triển khai một hệ thống tạo đối tượng người với phạm vi kiểm thử toàn diện.

Bạn chỉ cần chỉnh sửa tệp person_creator.py, làm theo các chú thích TODO hướng dẫn cách triển khai. Tệp này có cấu trúc lớp để tạo và quản lý các đối tượng người với nhiều thuộc tính khác nhau.

Tự làm thử

from person_creator import create_person

# Xử lý toàn diện các test case
test_case = input()

if test_case == "basic_test":
    create_person(name="John", age=25, occupation="Engineer")
    # Đầu ra:
    # Person created with properties:
    # name: John
    # age: 25
    # occupation: Engineer

elif test_case == "empty_test":
    create_person()
    # Đầu ra:
    # Person created with properties:
    # (không có thêm đầu ra vì không có thuộc tính nào)

elif test_case == "many_properties":
    create_person(name="Alice", age=30, occupation="Doctor", city="New York", 
                 country="USA", hobby="Reading", email="alice@example.com")
    # Đầu ra:
    # 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")
    # Đầu ra:
    # 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)
    # Đầu ra:
    # 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)
    # Đầu ra:
    # 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"})
    # Đầu ra:
    # 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")
    # Đầu ra:
    # Person created with properties:
    # name: José
    # city: São Paulo
    # country: Brasil
quiz iconTự kiểm tra

Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.

Tất cả bài học trong Lập trình hướng đối tượng

Tự luyện tập: Trình biên dịch Python online