Hướng dẫn get argument python - lấy đối số python

Xem bây giờ hướng dẫn này có một khóa học video liên quan được tạo bởi nhóm Python thực sự. Xem nó cùng với hướng dẫn bằng văn bản để hiểu sâu hơn về sự hiểu biết của bạn: Xác định các chức năng Python với các đối số tùy chọn This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Defining Python Functions With Optional Arguments

Show

Nội phân chính

  • Tạo các chức năng trong Python để sử dụng lại mã
  • Xác định các chức năng không có tham số đầu vào
  • Xác định các chức năng với các đối số đầu vào cần thiết
  • Sử dụng các đối số tùy chọn Python với các giá trị mặc định
  • Giá trị mặc định được gán cho tham số đầu vào
  • Giá trị đối số mặc định chung
  • Các loại dữ liệu không nên được sử dụng làm đối số mặc định
  • Sử dụng args và kwargs
  • Chức năng chấp nhận bất kỳ số lượng đối số nào
  • Chức năng chấp nhận bất kỳ số lượng đối số từ khóa nào

Nội phân chính

  • Tạo các chức năng trong Python để sử dụng lại mã
  • Xác định các chức năng không có tham số đầu vào
  • Xác định các chức năng với các đối số đầu vào cần thiết
  • Sử dụng các đối số tùy chọn Python với các giá trị mặc định
  • Giá trị mặc định được gán cho tham số đầu vào
  • Giá trị đối số mặc định chung
  • Các loại dữ liệu không nên được sử dụng làm đối số mặc định
  • Sử dụng args và kwargs
  • Chức năng chấp nhận bất kỳ số lượng đối số nào
  • Chức năng chấp nhận bất kỳ số lượng đối số từ khóa nào

Xác định chức năng của riêng bạn là một kỹ năng thiết yếu để viết mã sạch và hiệu quả. Trong hướng dẫn này, bạn sẽ khám phá các kỹ thuật bạn có sẵn để xác định các chức năng Python có các đối số tùy chọn. Khi bạn thành thạo các đối số tùy chọn Python, bạn sẽ có thể xác định các chức năng mạnh mẽ hơn và linh hoạt hơn.

Trong hướng dẫn này, bạn sẽ học:

  • Sự khác biệt là gì giữa các tham số và đối sốparameters and arguments
  • Cách xác định các chức năng với các đối số tùy chọn và giá trị tham số mặc địnhoptional arguments and default parameter values
  • Cách xác định các chức năng bằng cách sử dụng
    # optional_params.py
    
    shopping_list = {}
    
    # ...
    
    def add_item(item_name, quantity):
        if item_name in shopping_list.keys():
            shopping_list[item_name] += quantity
        else:
            shopping_list[item_name] = quantity
    
    add_item("Bread", 1)
    print(shopping_list)
    
    8 và
    # optional_params.py
    
    shopping_list = {}
    
    # ...
    
    def add_item(item_name, quantity):
        if item_name in shopping_list.keys():
            shopping_list[item_name] += quantity
        else:
            shopping_list[item_name] = quantity
    
    add_item("Bread", 1)
    print(shopping_list)
    
    9
    # optional_params.py
    
    shopping_list = {}
    
    # ...
    
    def add_item(item_name, quantity):
        if item_name in shopping_list.keys():
            shopping_list[item_name] += quantity
        else:
            shopping_list[item_name] = quantity
    
    add_item("Bread", 1)
    print(shopping_list)
    
    8
    and
    # optional_params.py
    
    shopping_list = {}
    
    # ...
    
    def add_item(item_name, quantity):
        if item_name in shopping_list.keys():
            shopping_list[item_name] += quantity
        else:
            shopping_list[item_name] = quantity
    
    add_item("Bread", 1)
    print(shopping_list)
    
    9
  • Cách xử lý các thông báo lỗi về các đối số tùy chọnerror messages about optional arguments

Để tận dụng tối đa hướng dẫn này, bạn sẽ cần một số quen thuộc với việc xác định các chức năng với các đối số cần thiết.

Tạo các chức năng trong Python để sử dụng lại mã

Bạn có thể nghĩ về một chức năng như một chương trình nhỏ chạy trong một chương trình khác hoặc trong một chức năng khác. Chương trình chính gọi chương trình nhỏ và gửi thông tin rằng chương trình mini sẽ cần khi nó chạy. Khi chức năng hoàn thành tất cả các hành động của mình, nó có thể gửi một số dữ liệu trở lại chương trình chính đã gọi nó.

Mục đích chính của một hàm là cho phép bạn sử dụng lại mã trong đó bất cứ khi nào bạn cần, sử dụng các đầu vào khác nhau nếu được yêu cầu.

Khi bạn sử dụng các chức năng, bạn đang mở rộng từ vựng Python của mình. Điều này cho phép bạn thể hiện giải pháp cho vấn đề của bạn một cách rõ ràng và cô đọng hơn.

Trong Python, theo quy ước, bạn nên đặt tên cho một hàm bằng cách sử dụng các chữ cái viết thường với các từ được phân tách bằng dấu gạch dưới, chẳng hạn như

$ python optional_params.py
{'Bread': 1}
0. Những quy ước này được mô tả trong PEP 8, đó là hướng dẫn phong cách Python. Bạn cần phải thêm dấu ngoặc đơn sau tên hàm khi bạn gọi nó. Vì các chức năng đại diện cho các hành động, nên nó là một thực tiễn tốt nhất để bắt đầu tên hàm của bạn bằng một động từ để làm cho mã của bạn dễ đọc hơn.

Xác định các chức năng không có tham số đầu vào

Trong hướng dẫn này, bạn sẽ sử dụng ví dụ về một chương trình cơ bản tạo ra và duy trì danh sách mua sắm và in nó ra khi bạn đã sẵn sàng đi đến siêu thị.

Bắt đầu bằng cách tạo một danh sách mua sắm:

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

Bạn sử dụng một từ điển để lưu trữ tên vật phẩm làm khóa và số lượng bạn cần mua của từng mặt hàng làm giá trị. Bạn có thể xác định một chức năng để hiển thị danh sách mua sắm:

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()

Khi bạn chạy tập lệnh này, bạn sẽ nhận được một bản in của danh sách mua sắm:

$ python optional_params.py
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee

Hàm mà bạn đã xác định không có tham số đầu vào vì dấu ngoặc đơn trong chữ ký hàm trống. Chữ ký là dòng đầu tiên trong định nghĩa hàm:signature are empty. The signature is the first line in the function definition:

Bạn không cần bất kỳ tham số đầu vào nào trong ví dụ này vì từ điển

$ python optional_params.py
{'Bread': 1}
1 là một biến toàn cầu. Điều này có nghĩa là nó có thể được truy cập từ mọi nơi trong chương trình, bao gồm từ bên trong định nghĩa chức năng. Đây được gọi là phạm vi toàn cầu. Bạn có thể đọc thêm về phạm vi trong phạm vi Python & Quy tắc LEGB: Giải quyết tên trong mã của bạn.global variable. This means that it can be accessed from everywhere in the program, including from within the function definition. This is called the global scope. You can read more about scope in Python Scope & the LEGB Rule: Resolving Names in Your Code.

Sử dụng các biến toàn cầu theo cách này không phải là một thực tiễn tốt. Nó có thể dẫn đến một số chức năng thực hiện các thay đổi đối với cùng một cấu trúc dữ liệu, có thể dẫn đến các lỗi khó tìm. Bạn sẽ thấy cách cải thiện điều này sau này trong hướng dẫn này khi bạn sẽ chuyển từ điển cho chức năng như một đối số.

Trong phần tiếp theo, bạn sẽ xác định một hàm có tham số đầu vào.

Xác định các chức năng với các đối số đầu vào cần thiết

Thay vì viết danh sách mua sắm trực tiếp trong mã, giờ đây bạn có thể khởi tạo một từ điển trống và viết một chức năng cho phép bạn thêm các mặt hàng vào danh sách mua sắm:

# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)

Hàm lặp đi lặp lại thông qua các phím từ điển, và nếu khóa tồn tại, số lượng được tăng lên. Nếu mục không phải là một trong các khóa, khóa được tạo và giá trị của

$ python optional_params.py
{'Bread': 1}
2 được gán cho nó. Bạn có thể chạy tập lệnh này để hiển thị từ điển in:

$ python optional_params.py
{'Bread': 1}

Bạn đã bao gồm hai tham số trong Chữ ký chức năng:parameters in the function signature:

  1. $ python optional_params.py
    {'Bread': 1}
    
    3
  2. $ python optional_params.py
    {'Bread': 1}
    
    4

Các tham số don lồng có bất kỳ giá trị nào. Các tên tham số được sử dụng trong mã trong định nghĩa hàm. Khi bạn gọi hàm, bạn chuyển các đối số trong dấu ngoặc đơn, một cho mỗi tham số. Một đối số là một giá trị bạn chuyển đến hàm.arguments within the parentheses, one for each parameter. An argument is a value you pass to the function.

Sự khác biệt giữa các tham số và đối số thường có thể bị bỏ qua. Nó là một sự khác biệt tinh tế nhưng quan trọng. Đôi khi bạn có thể tìm thấy các tham số được gọi là các tham số chính thức và đối số là các tham số thực tế.formal parameters and arguments as actual parameters.

Các đối số bạn nhập khi gọi

$ python optional_params.py
{'Bread': 1}
5 được yêu cầu đối số. Nếu bạn cố gắng gọi chức năng mà không có các đối số, bạn sẽ gặp lỗi:

# optional_params.py

shopping_list = {}

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item()
print(shopping_list)

TraceBack sẽ đưa ra một

$ python optional_params.py
{'Bread': 1}
6 nói rằng các đối số được yêu cầu:

$ python optional_params.py
Traceback (most recent call last):
  File "optional_params.py", line 11, in 
    add_item()
TypeError: add_item() missing 2 required positional arguments: 'item_name' and 'quantity'

Bạn sẽ xem xét nhiều thông báo lỗi liên quan đến việc sử dụng sai số đối số hoặc sử dụng chúng theo thứ tự sai, trong phần sau của hướng dẫn này.

Sử dụng các đối số tùy chọn Python với các giá trị mặc định

Trong phần này, bạn sẽ học cách xác định một hàm có một đối số tùy chọn. Các chức năng với các đối số tùy chọn cung cấp sự linh hoạt hơn trong cách bạn có thể sử dụng chúng. Bạn có thể gọi hàm có hoặc không có đối số và nếu không có đối số trong lệnh gọi hàm, thì giá trị mặc định được sử dụng.

Giá trị mặc định được gán cho tham số đầu vào

Bạn có thể sửa đổi chức năng

$ python optional_params.py
{'Bread': 1}
5 để tham số
$ python optional_params.py
{'Bread': 1}
4 có giá trị mặc định:

# optional_params.py

shopping_list = {}

def add_item(item_name, quantity=1):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread")
add_item("Milk", 2)
print(shopping_list)

Trong chữ ký chức năng, bạn đã thêm giá trị mặc định

$ python optional_params.py
{'Bread': 1}
2 vào tham số
$ python optional_params.py
{'Bread': 1}
4. Điều này không có nghĩa là giá trị của
$ python optional_params.py
{'Bread': 1}
4 sẽ luôn là
$ python optional_params.py
{'Bread': 1}
2. Nếu bạn chuyển một đối số tương ứng với
$ python optional_params.py
{'Bread': 1}
4 khi bạn gọi hàm, thì đối số đó sẽ được sử dụng làm giá trị cho tham số. Tuy nhiên, nếu bạn không vượt qua bất kỳ đối số nào, thì giá trị mặc định sẽ được sử dụng.

Các tham số với các giá trị mặc định có thể được theo sau bởi các tham số thông thường. Bạn sẽ đọc thêm về thứ tự mà bạn có thể xác định các tham số sau này trong hướng dẫn này.

Hàm

$ python optional_params.py
{'Bread': 1}
5 hiện có một tham số bắt buộc và một tham số tùy chọn. Trong ví dụ mã ở trên, bạn gọi
$ python optional_params.py
{'Bread': 1}
5 hai lần. Cuộc gọi chức năng đầu tiên của bạn có một đối số duy nhất, tương ứng với tham số cần thiết
$ python optional_params.py
{'Bread': 1}
3. Trong trường hợp này,
$ python optional_params.py
{'Bread': 1}
4 mặc định là
$ python optional_params.py
{'Bread': 1}
2. Cuộc gọi chức năng thứ hai của bạn có hai đối số, vì vậy giá trị mặc định được sử dụng trong trường hợp này. Bạn có thể thấy đầu ra của điều này dưới đây:

$ python optional_params.py
{'Bread': 1, 'Milk': 2}

Bạn cũng có thể chuyển các đối số cần thiết và tùy chọn vào một hàm là đối số từ khóa. Đối số từ khóa cũng có thể được gọi là đối số đã đặt tên:keyword arguments. Keyword arguments can also be referred to as named arguments:

add_item(item_name="Milk", quantity=2)

Bây giờ bạn có thể xem lại chức năng đầu tiên mà bạn đã xác định trong hướng dẫn này và tái cấu trúc nó để nó cũng chấp nhận một đối số mặc định:

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
0

Bây giờ khi bạn sử dụng

# optional_params.py

shopping_list = {}

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item()
print(shopping_list)
9, bạn có thể gọi nó không có đối số đầu vào hoặc chuyển giá trị boolean làm đối số cờ. Nếu bạn không vượt qua bất kỳ đối số nào khi gọi chức năng, thì danh sách mua sắm sẽ được hiển thị bằng cách hiển thị từng mục và số lượng của mục. Hàm sẽ hiển thị cùng một đầu ra nếu bạn vượt qua
$ python optional_params.py
Traceback (most recent call last):
  File "optional_params.py", line 11, in 
    add_item()
TypeError: add_item() missing 2 required positional arguments: 'item_name' and 'quantity'
0 dưới dạng đối số khi gọi hàm. Tuy nhiên, nếu bạn sử dụng
$ python optional_params.py
Traceback (most recent call last):
  File "optional_params.py", line 11, in 
    add_item()
TypeError: add_item() missing 2 required positional arguments: 'item_name' and 'quantity'
1, chỉ có tên mục được hiển thị.flag argument. If you don’t pass any arguments when calling the function, then the shopping list is displayed by showing each item’s name and quantity. The function will display the same output if you pass
$ python optional_params.py
Traceback (most recent call last):
  File "optional_params.py", line 11, in 
    add_item()
TypeError: add_item() missing 2 required positional arguments: 'item_name' and 'quantity'
0 as an argument when calling the function. However, if you use
$ python optional_params.py
Traceback (most recent call last):
  File "optional_params.py", line 11, in 
    add_item()
TypeError: add_item() missing 2 required positional arguments: 'item_name' and 'quantity'
1, only the item names are displayed.

Bạn nên tránh sử dụng cờ trong trường hợp giá trị của cờ làm thay đổi đáng kể hành vi của chức năng. Một chức năng chỉ nên chịu trách nhiệm cho một điều. Nếu bạn muốn một lá cờ để đẩy chức năng vào một đường dẫn thay thế, bạn có thể xem xét việc viết một chức năng riêng biệt.

Giá trị đối số mặc định chung

Trong các ví dụ bạn đã làm việc ở trên, bạn đã sử dụng số nguyên

$ python optional_params.py
{'Bread': 1}
2 làm giá trị mặc định trong một trường hợp và giá trị boolean
$ python optional_params.py
Traceback (most recent call last):
  File "optional_params.py", line 11, in 
    add_item()
TypeError: add_item() missing 2 required positional arguments: 'item_name' and 'quantity'
0 trong cái kia. Đây là những giá trị mặc định phổ biến mà bạn sẽ tìm thấy trong các định nghĩa chức năng. Tuy nhiên, kiểu dữ liệu bạn nên sử dụng cho các giá trị mặc định phụ thuộc vào hàm bạn xác định và cách bạn muốn chức năng được sử dụng.

Các số nguyên

$ python optional_params.py
Traceback (most recent call last):
  File "optional_params.py", line 11, in 
    add_item()
TypeError: add_item() missing 2 required positional arguments: 'item_name' and 'quantity'
4 và
$ python optional_params.py
{'Bread': 1}
2 là các giá trị mặc định phổ biến để sử dụng khi giá trị tham số của tham số cần phải là một số nguyên. Điều này là do
$ python optional_params.py
Traceback (most recent call last):
  File "optional_params.py", line 11, in 
    add_item()
TypeError: add_item() missing 2 required positional arguments: 'item_name' and 'quantity'
4 và
$ python optional_params.py
{'Bread': 1}
2 thường là các giá trị dự phòng hữu ích cần có. Trong hàm
$ python optional_params.py
{'Bread': 1}
5 bạn đã viết trước đó, đặt số lượng cho một mục mới thành
$ python optional_params.py
{'Bread': 1}
2 là tùy chọn hợp lý nhất.

Tuy nhiên, nếu bạn có thói quen mua hai thứ bạn mua khi bạn vào siêu thị, thì việc đặt giá trị mặc định thành

# optional_params.py

shopping_list = {}

def add_item(item_name, quantity=1):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread")
add_item("Milk", 2)
print(shopping_list)
0 có thể phù hợp hơn với bạn.

Khi tham số đầu vào cần phải là một chuỗi, giá trị mặc định chung để sử dụng là chuỗi trống (

# optional_params.py

shopping_list = {}

def add_item(item_name, quantity=1):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread")
add_item("Milk", 2)
print(shopping_list)
1). Điều này gán một giá trị có kiểu dữ liệu là chuỗi nhưng không đặt vào bất kỳ ký tự bổ sung nào. Bạn có thể sửa đổi
$ python optional_params.py
{'Bread': 1}
5 để cả hai đối số là tùy chọn:

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
1

Bạn đã sửa đổi hàm để cả hai tham số có giá trị mặc định và do đó hàm có thể được gọi không có tham số đầu vào:

Dòng mã này sẽ thêm một mục vào từ điển

$ python optional_params.py
{'Bread': 1}
1 với một chuỗi trống làm khóa và giá trị là
$ python optional_params.py
{'Bread': 1}
2. Nó khá phổ biến để kiểm tra xem một đối số đã được thông qua khi hàm được gọi và chạy một số mã phù hợp. Bạn có thể thay đổi chức năng trên để làm điều này:

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
2

Trong phiên bản này, nếu không có mục nào được chuyển đến hàm, hàm sẽ đặt số lượng thành

$ python optional_params.py
Traceback (most recent call last):
  File "optional_params.py", line 11, in 
    add_item()
TypeError: add_item() missing 2 required positional arguments: 'item_name' and 'quantity'
4. Chuỗi trống có giá trị giả, có nghĩa là
# optional_params.py

shopping_list = {}

def add_item(item_name, quantity=1):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread")
add_item("Milk", 2)
print(shopping_list)
6 trả về
# optional_params.py

shopping_list = {}

def add_item(item_name, quantity=1):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread")
add_item("Milk", 2)
print(shopping_list)
7, trong khi bất kỳ chuỗi nào khác sẽ có giá trị sự thật. Khi một từ khóa
# optional_params.py

shopping_list = {}

def add_item(item_name, quantity=1):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread")
add_item("Milk", 2)
print(shopping_list)
8 được theo sau bởi một giá trị sự thật hoặc giả, câu lệnh
# optional_params.py

shopping_list = {}

def add_item(item_name, quantity=1):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread")
add_item("Milk", 2)
print(shopping_list)
8 sẽ giải thích những điều này là
$ python optional_params.py
Traceback (most recent call last):
  File "optional_params.py", line 11, in 
    add_item()
TypeError: add_item() missing 2 required positional arguments: 'item_name' and 'quantity'
0 hoặc
# optional_params.py

shopping_list = {}

def add_item(item_name, quantity=1):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread")
add_item("Milk", 2)
print(shopping_list)
7. Bạn có thể đọc thêm về các giá trị Truthy và Falsy trong Python Booleans: Tối ưu hóa mã của bạn với các giá trị sự thật.falsy value, which means that
# optional_params.py

shopping_list = {}

def add_item(item_name, quantity=1):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread")
add_item("Milk", 2)
print(shopping_list)
6 returns
# optional_params.py

shopping_list = {}

def add_item(item_name, quantity=1):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread")
add_item("Milk", 2)
print(shopping_list)
7, whereas any other string will have a truthy value. When an
# optional_params.py

shopping_list = {}

def add_item(item_name, quantity=1):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread")
add_item("Milk", 2)
print(shopping_list)
8 keyword is followed by a truthy or falsy value, the
# optional_params.py

shopping_list = {}

def add_item(item_name, quantity=1):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread")
add_item("Milk", 2)
print(shopping_list)
8 statement will interpret these as
$ python optional_params.py
Traceback (most recent call last):
  File "optional_params.py", line 11, in 
    add_item()
TypeError: add_item() missing 2 required positional arguments: 'item_name' and 'quantity'
0 or
# optional_params.py

shopping_list = {}

def add_item(item_name, quantity=1):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread")
add_item("Milk", 2)
print(shopping_list)
7. You can read more about truthy and falsy values in Python Booleans: Optimize Your Code With Truth Values.

Do đó, bạn có thể sử dụng biến trực tiếp trong câu lệnh

# optional_params.py

shopping_list = {}

def add_item(item_name, quantity=1):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread")
add_item("Milk", 2)
print(shopping_list)
8 để kiểm tra xem một đối số tùy chọn có được sử dụng hay không.

Một giá trị phổ biến khác mà Lừa thường được sử dụng làm giá trị mặc định là

$ python optional_params.py
{'Bread': 1, 'Milk': 2}
3. Đây là cách đại diện cho Python, mặc dù nó thực sự là một đối tượng đại diện cho giá trị null. Bạn sẽ thấy một ví dụ về khi
$ python optional_params.py
{'Bread': 1, 'Milk': 2}
3 là một giá trị mặc định hữu ích để sử dụng trong phần tiếp theo.

Các loại dữ liệu không nên được sử dụng làm đối số mặc định

Bạn đã sử dụng số nguyên và chuỗi làm giá trị mặc định trong các ví dụ ở trên và

$ python optional_params.py
{'Bread': 1, 'Milk': 2}
3 là một giá trị mặc định phổ biến khác. Đây không phải là loại dữ liệu duy nhất bạn có thể sử dụng làm giá trị mặc định. Tuy nhiên, không phải tất cả các loại dữ liệu nên được sử dụng.

Trong phần này, bạn sẽ thấy lý do tại sao các loại dữ liệu có thể thay đổi không nên được sử dụng làm giá trị mặc định trong các định nghĩa chức năng. Một đối tượng có thể thay đổi là một đối tượng có giá trị có thể được thay đổi, chẳng hạn như danh sách hoặc từ điển. Bạn có thể tìm hiểu thêm về các loại dữ liệu có thể thay đổi và bất biến trong tính bất biến trong Python và trong tài liệu chính thức của Python.mutable data types should not be used as default values in function definitions. A mutable object is one whose values can be changed, such as a list or a dictionary. You can find out more about mutable and immutable data types in Immutability in Python and in Python’s official documentation.

Bạn có thể thêm từ điển chứa các tên và số lượng mục dưới dạng tham số đầu vào vào hàm bạn đã xác định trước đó. Bạn có thể bắt đầu bằng cách thực hiện tất cả các đối số cần thiết:

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
3

Bây giờ bạn có thể chuyển

$ python optional_params.py
{'Bread': 1}
1 cho chức năng khi bạn gọi nó. Điều này làm cho chức năng khép kín hơn vì nó không dựa vào một biến gọi là
$ python optional_params.py
{'Bread': 1}
1 để tồn tại trong phạm vi mà Lọ gọi hàm. Thay đổi này cũng làm cho chức năng linh hoạt hơn khi bạn có thể sử dụng nó với các từ điển đầu vào khác nhau.

Bạn cũng đã thêm câu lệnh

$ python optional_params.py
{'Bread': 1, 'Milk': 2}
8 để trả về từ điển đã sửa đổi. Dòng này về mặt kỹ thuật không được yêu cầu ở giai đoạn này vì từ điển là một loại dữ liệu có thể thay đổi và do đó hàm sẽ thay đổi trạng thái của từ điển tồn tại trong mô -đun chính. Tuy nhiên, bạn sẽ cần câu lệnh
$ python optional_params.py
{'Bread': 1, 'Milk': 2}
8 sau khi bạn đưa ra đối số này tùy chọn, vì vậy, tốt nhất là bao gồm nó ngay bây giờ.

Để gọi chức năng, bạn sẽ cần gán dữ liệu được trả về bởi hàm cho một biến:

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
4

Bạn cũng có thể thêm tham số

$ python optional_params.py
{'Bread': 1}
1 vào
# optional_params.py

shopping_list = {}

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item()
print(shopping_list)
9, hàm đầu tiên bạn xác định trong hướng dẫn này. Bây giờ bạn có thể có một số danh sách mua sắm trong chương trình của mình và sử dụng các chức năng tương tự để thêm các mặt hàng và hiển thị danh sách mua sắm:

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
5

Bạn có thể thấy đầu ra của mã này dưới đây. Danh sách các mặt hàng để mua từ cửa hàng phần cứng được hiển thị đầu tiên. Phần thứ hai của đầu ra hiển thị các mục cần thiết từ siêu thị:

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
6

Bây giờ, bạn sẽ thêm một giá trị mặc định cho tham số

$ python optional_params.py
{'Bread': 1}
1 trong
$ python optional_params.py
{'Bread': 1}
5 để nếu không có từ điển nào được chuyển đến hàm, thì một từ điển trống được sử dụng. Tùy chọn hấp dẫn nhất là làm cho giá trị mặc định thành một từ điển trống. Bạn sẽ thấy lý do tại sao đây không phải là một ý tưởng tốt, nhưng bạn có thể thử tùy chọn này ngay bây giờ:

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
7

Khi bạn chạy tập lệnh này, bạn sẽ nhận được đầu ra bên dưới hiển thị các mặt hàng cần thiết từ cửa hàng quần áo, có thể tạo ấn tượng rằng mã này hoạt động như dự định:

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
8

Tuy nhiên, mã này có lỗ hổng nghiêm trọng có thể dẫn đến kết quả bất ngờ và sai. Bạn có thể thêm một danh sách mua sắm mới cho các mặt hàng cần thiết từ cửa hàng điện tử bằng cách sử dụng

$ python optional_params.py
{'Bread': 1}
5 mà không có đối số tương ứng với
$ python optional_params.py
{'Bread': 1}
1. Điều này dẫn đến giá trị mặc định đang được sử dụng, mà bạn hy vọng sẽ tạo ra một từ điển trống mới:

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
9

Bạn sẽ thấy vấn đề khi bạn nhìn vào đầu ra từ mã này:

$ python optional_params.py
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
0

Cả hai danh sách mua sắm đều giống hệt nhau mặc dù bạn đã chỉ định đầu ra từ

$ python optional_params.py
{'Bread': 1}
5 cho các biến khác nhau mỗi khi bạn gọi hàm. Vấn đề xảy ra vì từ điển là một loại dữ liệu có thể thay đổi.

Bạn đã gán một từ điển trống làm giá trị mặc định cho tham số

$ python optional_params.py
{'Bread': 1}
1 khi bạn xác định hàm. Lần đầu tiên bạn gọi hàm, từ điển này trống rỗng. Tuy nhiên, vì từ điển là một loại có thể thay đổi, khi bạn gán các giá trị cho từ điển, từ điển mặc định không còn trống.

Khi bạn gọi hàm lần thứ hai và giá trị mặc định cho

$ python optional_params.py
{'Bread': 1}
1 được yêu cầu một lần nữa, từ điển mặc định không còn trống vì nó đã được điền vào lần đầu tiên bạn gọi hàm. Vì bạn đã gọi cùng một hàm, bạn đã sử dụng cùng một từ điển mặc định được lưu trữ trong bộ nhớ.

Hành vi này không xảy ra với các loại dữ liệu bất biến. Giải pháp cho vấn đề này là sử dụng một giá trị mặc định khác, chẳng hạn như

$ python optional_params.py
{'Bread': 1, 'Milk': 2}
3, sau đó tạo một từ điển trống trong hàm khi không có đối số tùy chọn nào được truyền:

$ python optional_params.py
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
1

Bạn có thể kiểm tra xem một từ điển đã được thông qua như một đối số bằng cách sử dụng câu lệnh

# optional_params.py

shopping_list = {}

def add_item(item_name, quantity=1):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread")
add_item("Milk", 2)
print(shopping_list)
8. Bạn không nên dựa vào bản chất giả của
$ python optional_params.py
{'Bread': 1, 'Milk': 2}
3 mà thay vào đó kiểm tra rõ ràng rằng đối số là
$ python optional_params.py
{'Bread': 1, 'Milk': 2}
3. Dựa vào thực tế là
$ python optional_params.py
{'Bread': 1, 'Milk': 2}
3 sẽ được coi là một giá trị sai có thể gây ra vấn đề nếu một đối số khác bị ảnh hưởng.

Bây giờ khi bạn chạy lại tập lệnh của mình, bạn sẽ nhận được đầu ra chính xác vì một từ điển mới được tạo mỗi lần bạn sử dụng hàm với giá trị mặc định cho

$ python optional_params.py
{'Bread': 1}
1:

$ python optional_params.py
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
2

Bạn nên luôn luôn tránh sử dụng kiểu dữ liệu có thể thay đổi làm giá trị mặc định khi xác định hàm với các tham số tùy chọn.

Sử dụng args và kwargs

Có hai loại đối số tùy chọn Python khác mà bạn sẽ cần biết. Trong các phần trước của hướng dẫn này, bạn đã học cách tạo một chức năng với một đối số tùy chọn. Nếu bạn cần nhiều đối số tùy chọn hơn, bạn có thể tạo thêm tham số với các giá trị mặc định khi xác định hàm.

Tuy nhiên, có thể xác định một hàm chấp nhận bất kỳ số lượng đối số tùy chọn nào. Bạn thậm chí có thể xác định các chức năng chấp nhận bất kỳ số lượng đối số từ khóa. Đối số từ khóa là các đối số có từ khóa và giá trị liên quan đến chúng, như bạn sẽ học trong các phần sắp tới.

Để xác định các chức năng với số lượng các đối số đầu vào và từ khóa, bạn sẽ cần phải tìm hiểu về

# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
8 và
# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
9. Trong hướng dẫn này, chúng tôi sẽ xem xét những điểm quan trọng nhất mà bạn cần biết về những lập luận tùy chọn Python này. Bạn có thể khám phá
# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
8 và
# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
9 nữa nếu bạn muốn tìm hiểu thêm.

Chức năng chấp nhận bất kỳ số lượng đối số nào

Trước khi xác định một hàm chấp nhận bất kỳ số lượng đối số nào, bạn sẽ cần phải làm quen với toán tử giải nén. Bạn có thể bắt đầu với một danh sách như bảng sau:

>>>

$ python optional_params.py
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
3

Biến

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
09 điểm vào danh sách và lần lượt, danh sách có bốn mục trong đó. Nếu bạn sử dụng
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
09 như một đối số cho
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
11, thì bạn sẽ chuyển một biến cho
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
11:

>>>

$ python optional_params.py
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
4

Biến

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
09 điểm vào danh sách và lần lượt, danh sách có bốn mục trong đó. Nếu bạn sử dụng
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
09 như một đối số cho
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
11, thì bạn sẽ chuyển một biến cho
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
11:

>>>

$ python optional_params.py
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
5

Biến

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
09 điểm vào danh sách và lần lượt, danh sách có bốn mục trong đó. Nếu bạn sử dụng
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
09 như một đối số cho
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
11, thì bạn sẽ chuyển một biến cho
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
11:

>>>

$ python optional_params.py
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
6

Biến

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
09 điểm vào danh sách và lần lượt, danh sách có bốn mục trong đó. Nếu bạn sử dụng
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
09 như một đối số cho
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
11, thì bạn sẽ chuyển một biến cho
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
11:

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
11 hiển thị danh sách, như bạn mong đợi. Tuy nhiên, nếu bạn phải sử dụng
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
14 trong dấu ngoặc đơn của
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
11, bạn sẽ nhận được một kết quả khác:

Lần này,

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
11 hiển thị bốn chuỗi riêng biệt hơn là danh sách. Điều này tương đương với việc viết như sau:

Khi biểu hiện dấu hoa thị hoặc biểu tượng sao (

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
17) được sử dụng ngay trước một chuỗi, chẳng hạn như
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
09, nó sẽ giải nén chuỗi vào các thành phần riêng lẻ của nó. Khi một chuỗi như một danh sách được giải nén, các mục của nó được trích xuất và xử lý như các đối tượng riêng lẻ.

$ python optional_params.py
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
7

Bạn có thể nhận thấy rằng

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
11 có thể lấy bất kỳ số lượng đối số nào. Bạn đã sử dụng nó với một đối số đầu vào và với bốn đối số đầu vào trong các ví dụ trên. Bạn cũng có thể sử dụng
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
11 với dấu ngoặc đơn trống và nó sẽ in một dòng trống.

$ python optional_params.py
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
8

Đối số đầu tiên khi gọi

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
21 là một đối số bắt buộc. Theo đối số đầu tiên, hàm có thể chấp nhận bất kỳ số lượng đối số bổ sung. Trong trường hợp này, bạn đã thêm bốn đối số bổ sung khi gọi hàm. Ở đây, đầu ra của mã trên:

$ python optional_params.py
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
9

Bạn có thể hiểu những gì xảy ra với tham số

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
28 bằng cách xem xét một ví dụ đơn giản hóa:

>>>

# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
0

Khi bạn hiển thị kiểu dữ liệu, bạn có thể thấy rằng

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
28 là một tuple. Do đó, tất cả các đối số bổ sung được gán là các mục trong bộ tple
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
28. Sau đó, bạn có thể sử dụng bộ dữ liệu này trong định nghĩa hàm như bạn đã làm trong định nghĩa chính của
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
21 ở trên, trong đó bạn đã lặp lại thông qua tuple
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
28 bằng cách sử dụng vòng lặp
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
33.

Điều này không giống như truyền một tuple như một đối số trong cuộc gọi chức năng. Sử dụng

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
34 cho phép bạn sử dụng chức năng linh hoạt hơn khi bạn có thể thêm nhiều đối số như bạn muốn mà không cần phải đặt chúng vào một bản gọi trong cuộc gọi chức năng.

Nếu bạn không thêm bất kỳ đối số bổ sung nào khi bạn gọi chức năng, thì Tuple sẽ trống:

>>>

# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
1

Khi bạn hiển thị kiểu dữ liệu, bạn có thể thấy rằng

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
28 là một tuple. Do đó, tất cả các đối số bổ sung được gán là các mục trong bộ tple
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
28. Sau đó, bạn có thể sử dụng bộ dữ liệu này trong định nghĩa hàm như bạn đã làm trong định nghĩa chính của
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
21 ở trên, trong đó bạn đã lặp lại thông qua tuple
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
28 bằng cách sử dụng vòng lặp
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
33.

Điều này không giống như truyền một tuple như một đối số trong cuộc gọi chức năng. Sử dụng # optional_params.py shopping_list = { "Bread": 1, "Milk": 2, "Chocolate": 1, "Butter": 1, "Coffee": 1, } def show_list(): for item_name, quantity in shopping_list.items(): print(f"{quantity}x {item_name}") show_list() 34 cho phép bạn sử dụng chức năng linh hoạt hơn khi bạn có thể thêm nhiều đối số như bạn muốn mà không cần phải đặt chúng vào một bản gọi trong cuộc gọi chức năng.

Nếu bạn không thêm bất kỳ đối số bổ sung nào khi bạn gọi chức năng, thì Tuple sẽ trống:

>>>

# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
2

Khi bạn hiển thị kiểu dữ liệu, bạn có thể thấy rằng

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
28 là một tuple. Do đó, tất cả các đối số bổ sung được gán là các mục trong bộ tple
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
28. Sau đó, bạn có thể sử dụng bộ dữ liệu này trong định nghĩa hàm như bạn đã làm trong định nghĩa chính của
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
21 ở trên, trong đó bạn đã lặp lại thông qua tuple
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
28 bằng cách sử dụng vòng lặp
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
33.

>>>

# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
3

Khi bạn hiển thị kiểu dữ liệu, bạn có thể thấy rằng

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
28 là một tuple. Do đó, tất cả các đối số bổ sung được gán là các mục trong bộ tple
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
28. Sau đó, bạn có thể sử dụng bộ dữ liệu này trong định nghĩa hàm như bạn đã làm trong định nghĩa chính của
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
21 ở trên, trong đó bạn đã lặp lại thông qua tuple
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
28 bằng cách sử dụng vòng lặp
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
33.

Điều này không giống như truyền một tuple như một đối số trong cuộc gọi chức năng. Sử dụng

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
34 cho phép bạn sử dụng chức năng linh hoạt hơn khi bạn có thể thêm nhiều đối số như bạn muốn mà không cần phải đặt chúng vào một bản gọi trong cuộc gọi chức năng.

# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
4

Nếu bạn không thêm bất kỳ đối số bổ sung nào khi bạn gọi chức năng, thì Tuple sẽ trống:mapping. A mapping is a data type that has paired values as items, such as a dictionary.

Khi bạn thêm

# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
8 vào định nghĩa hàm, bạn sẽ thường thêm chúng sau tất cả các tham số cần thiết và tùy chọn. Bạn có thể có các đối số chỉ có từ khóa tuân theo
# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
8, nhưng đối với hướng dẫn này, bạn có thể cho rằng
# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
8 thường sẽ được thêm vào sau tất cả các đối số khác, ngoại trừ
# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
9, mà bạn sẽ tìm hiểu trong phần sau.

# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
5

Chức năng chấp nhận bất kỳ số lượng đối số từ khóa nào

# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
6

Khi bạn xác định một hàm với các tham số, bạn có thể lựa chọn gọi hàm bằng đối số không phải là Keye từ hoặc đối số từ khóa:

>>>

# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
7

Khi bạn hiển thị kiểu dữ liệu, bạn có thể thấy rằng

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
28 là một tuple. Do đó, tất cả các đối số bổ sung được gán là các mục trong bộ tple
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
28. Sau đó, bạn có thể sử dụng bộ dữ liệu này trong định nghĩa hàm như bạn đã làm trong định nghĩa chính của
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
21 ở trên, trong đó bạn đã lặp lại thông qua tuple
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
28 bằng cách sử dụng vòng lặp
# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()
33.

Điều này không giống như truyền một tuple như một đối số trong cuộc gọi chức năng. Sử dụng # optional_params.py shopping_list = { "Bread": 1, "Milk": 2, "Chocolate": 1, "Butter": 1, "Coffee": 1, } def show_list(): for item_name, quantity in shopping_list.items(): print(f"{quantity}x {item_name}") show_list() 34 cho phép bạn sử dụng chức năng linh hoạt hơn khi bạn có thể thêm nhiều đối số như bạn muốn mà không cần phải đặt chúng vào một bản gọi trong cuộc gọi chức năng.

Nếu bạn không thêm bất kỳ đối số bổ sung nào khi bạn gọi chức năng, thì Tuple sẽ trống:

Khi bạn thêm

# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
8 vào định nghĩa hàm, bạn sẽ thường thêm chúng sau tất cả các tham số cần thiết và tùy chọn. Bạn có thể có các đối số chỉ có từ khóa tuân theo
# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
8, nhưng đối với hướng dẫn này, bạn có thể cho rằng
# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
8 thường sẽ được thêm vào sau tất cả các đối số khác, ngoại trừ
# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
9, mà bạn sẽ tìm hiểu trong phần sau.

  • Chức năng chấp nhận bất kỳ số lượng đối số từ khóa nàoparameters and arguments
  • Khi bạn xác định một hàm với các tham số, bạn có thể lựa chọn gọi hàm bằng đối số không phải là Keye từ hoặc đối số từ khóa:optional arguments and default parameter values
  • Trong cuộc gọi chức năng đầu tiên, các đối số được thông qua theo vị trí, trong khi trong lần thứ hai, họ đã vượt qua từ khóa. Nếu bạn sử dụng các đối số từ khóa, bạn không còn cần phải nhập các đối số theo thứ tự chúng được xác định:
    # optional_params.py
    
    shopping_list = {}
    
    # ...
    
    def add_item(item_name, quantity):
        if item_name in shopping_list.keys():
            shopping_list[item_name] += quantity
        else:
            shopping_list[item_name] = quantity
    
    add_item("Bread", 1)
    print(shopping_list)
    
    8
    and
    # optional_params.py
    
    shopping_list = {}
    
    # ...
    
    def add_item(item_name, quantity):
        if item_name in shopping_list.keys():
            shopping_list[item_name] += quantity
        else:
            shopping_list[item_name] = quantity
    
    add_item("Bread", 1)
    print(shopping_list)
    
    9
  • Bạn có thể thay đổi hành vi mặc định này bằng cách khai báo các đối số chỉ có vị trí hoặc đối số chỉ từ khóa.error messages about optional arguments

Khi xác định hàm, bạn có thể bao gồm bất kỳ số lượng đối số từ khóa tùy chọn nào được đưa vào bằng cách sử dụng

# optional_params.py

shopping_list = {}

# ...

def add_item(item_name, quantity):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item("Bread", 1)
print(shopping_list)
9, viết tắt của các đối số từ khóa. Chữ ký chức năng trông như thế này:

Tuy nhiên, kỹ năng chính mà bạn đã học được trong hướng dẫn này là xác định các chức năng của riêng bạn.Bây giờ bạn có thể bắt đầu viết các chức năng với các tham số cần thiết và tùy chọn và với số lượng đối số từ khóa và từ khóa không cần thiết.Nắm vững các kỹ năng này sẽ giúp bạn đưa mã hóa Python của bạn lên cấp độ tiếp theo.

Xem bây giờ hướng dẫn này có một khóa học video liên quan được tạo bởi nhóm Python thực sự.Xem nó cùng với hướng dẫn bằng văn bản để hiểu sâu hơn về sự hiểu biết của bạn: Xác định các chức năng Python với các đối số tùy chọn This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Defining Python Functions With Optional Arguments