Sunday, February 9, 2025

[Python] Lesson 24 – *Args

-

*args là một cú pháp trong Python được sử dụng để truyền một số lượng không xác định các tham số không tên vào một hàm. Các tham số được truyền vào được tổng hợp thành một tuple và có thể được truy cập trong hàm bằng cách sử dụng biến tuple args. Dưới đây là ba ví dụ về việc sử dụng *args:

Ví dụ tính tổng các số:

def sum(*args):
    total = 0
    for num in args:
        total += num
    return total

print(sum(1, 2, 3, 4, 5))  # output: 15

Ví dụ in các phần tử của một list:

def print_list(*args):
    for arg in args:
        print(arg)

lst = ['apple', 'banana', 'orange']
print_list(*lst)  # output: apple banana orange

Truyền nhiều tham số vào một hàm:

def my_function(name, *args):
    print(f"Hello, {name}!")
    print("Your additional parameters are:")
    for arg in args:
        print(arg)

my_function('Alice', 'apple', 'banana', 'orange')
# output: Hello, Alice!
#         Your additional parameters are:
#         apple
#         banana
#         orange

Giả sử bạn có một chương trình Python để lấy danh sách tên file từ thư mục và in ra thông tin tên file và đường dẫn tương ứng. Tuy nhiên, số lượng file và đường dẫn là không xác định trước đó, có thể nhiều hoặc ít hơn tùy vào nội dung của thư mục. Trong trường hợp này, chúng ta có thể sử dụng *args để xử lý số lượng đối số không xác định:

import os

def print_files(*args):
    for file_path in args:
        print("File name: {}, Path: {}".format(os.path.basename(file_path), os.path.abspath(file_path)))

# In ra thông tin của các file trong thư mục /home/user/Documents
print_files('/home/user/Documents/file1.txt', '/home/user/Documents/file2.txt', '/home/user/Documents/file3.txt')

# In ra thông tin của file trong thư mục /home/user/Downloads
print_files('/home/user/Downloads/file4.txt')

Khi gọi hàm print_files với các đối số không xác định trước, chúng ta có thể sử dụng *args để xử lý các đối số này mà không cần biết trước số lượng đối số.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

4,956FansLike
256FollowersFollow
223SubscribersSubscribe
spot_img

Related Stories