Hướng dẫn python keyword argument without default - đối số từ khóa python không có mặc định

Tôi đã quen với việc có các định nghĩa chức năng/phương thức như vậy trong Python:

Show
def my_function(arg1=None , arg2='default'):
    ... do stuff here

Nếu tôi không cung cấ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()
1 (hoặc
# 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), thì giá trị mặc đị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()
3 (hoặc
# 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) được chỉ định.

Tôi có thể chỉ định các đối số từ khóa như thế này, nhưng không có giá trị mặc định? Tôi hy vọng nó sẽ gây ra lỗi nếu đối số không được cung cấp.

Đã hỏi ngày 13 tháng 3 năm 2015 lúc 16:18Mar 13, 2015 at 16:18

Hướng dẫn python keyword argument without default - đối số từ khóa python không có mặc định

wobbily_colwobbily_colwobbily_col

10,8K12 Huy hiệu vàng58 Huy hiệu bạc82 Huy hiệu Đồng12 gold badges58 silver badges82 bronze badges

3

Bạn có thể trong Python hiện đại (3, nghĩa là):

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob

Đã trả lời ngày 13 tháng 3 năm 2015 lúc 16:25Mar 13, 2015 at 16:25

Hướng dẫn python keyword argument without default - đối số từ khóa python không có mặc định

4

Bất kỳ đối số nào cũng có thể được đưa ra như với biểu thức từ khóa, cho dù nó có mặc định hay không:

def foo(a, b):
    return a - b
foo(2, 1)         # Returns 1
foo(a=2, b=1)     # Returns 1
foo(b=2, a=1)     # Returns -1
foo()             # Raises an error

Nếu bạn muốn buộc các đối số chỉ là từ khóa, thì hãy xem câu trả lời của DSM, nhưng điều đó không giống như những gì bạn thực sự hỏi.

Đã trả lời ngày 13 tháng 3 năm 2015 lúc 17:13Mar 13, 2015 at 17:13

Hướng dẫn python keyword argument without default - đối số từ khóa python không có mặc định

Dolda2000Dolda2000Dolda2000

24.6K2 Huy hiệu vàng49 Huy hiệu bạc90 Huy hiệu Đồng2 gold badges49 silver badges90 bronze badges

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

Là từ khóa đối số python tùy chọn?

Bạn có thể gán một đối số tùy chọn bằng toán tử gán theo định nghĩa hàm hoặc sử dụng câu lệnh Python ** Kwargs. Có hai loại đối số Một hàm Python có thể chấp nhận: vị trí và tùy chọn. Đối số tùy chọn là các giá trị không cần được chỉ định cho một hàm được gọi.

  • 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 = {
        "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 và
    # 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
    # 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
    and
    # 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
  • 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

Một sự hiểu biết tốt về các đối số tùy chọn cũng sẽ giúp bạn sử dụng các chức năng trong thư viện tiêu chuẩn và trong các mô-đun bên thứ ba khác. Hiển thị tài liệu cho các chức năng này sẽ hiển thị cho bạn chữ ký chức năng mà bạn có thể xác định được đối số nào được yêu cầu, những chức năng nào là tùy chọn và cái nào là

# 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 hoặc
# 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.

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

Là từ khóa đối số python tùy chọn?

Bạn có thể gán một đối số tùy chọn bằng toán tử gán theo định nghĩa hàm hoặc sử dụng câu lệnh Python ** Kwargs. Có hai loại đối số Một hàm Python có thể chấp nhận: vị trí và tùy chọn. Đối số tùy chọn là các giá trị không cần được chỉ định cho một hàm được gọi.

Đối số chỉ từ khóa trong Python là gì?

Các đối số chỉ có từ khóa là một thuộc tính khác của các hàm Python đã có sẵn kể từ Python 3.0. Các đối số này được chỉ định bằng điểm đánh dấu '*'. Họ nhắc người dùng nêu từ khóa được sử dụng trong hàm đã được xác định khi thực hiện cuộc gọi đến cùng một chức năng.

Sự khác biệt giữa đối số từ khóa và đối số mặc định trong Python là gì?

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

# 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 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

# 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 đượ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
    1x Bread
    2x Milk
    1x Chocolate
    1x Butter
    1x Coffee
    
    0
  2. $ python optional_params.py
    1x Bread
    2x Milk
    1x Chocolate
    1x Butter
    1x Coffee
    
    1

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
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
2 là đối số yêu cầu. 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
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
3 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
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
2 để tham số
$ python optional_params.py
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
1 có giá trị mặc định:

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
0

Trong chữ ký chức năng, bạn đã thêm giá trị 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()
9 vào tham số
$ python optional_params.py
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
1. Điều này không có nghĩa là giá trị của
$ python optional_params.py
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
1 sẽ luôn là
# 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. Nếu bạn chuyển một đối số tương ứng với
$ python optional_params.py
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
1 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
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
2 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
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
2 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
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
0. Trong trường hợp này,
$ python optional_params.py
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
1 mặc định là
# 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. 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:

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
1

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:

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
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:

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
3

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("Bread", 1)
print(shopping_list)
6, 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
# 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 dưới dạng đối số khi gọi hàm. Tuy nhiên, nếu 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("Bread", 1)
print(shopping_list)
8, 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
# 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 as an argument when calling the function. However, if you use
# 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, 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

# 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 làm giá trị mặc định trong một trường hợp và giá trị boolean
# 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 trong cái khác. Đâ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
{'Bread': 1}
1 và
# 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 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
{'Bread': 1}
1 và
# 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 thường là các giá trị dự phòng hữu ích cần có. Trong hàm
$ python optional_params.py
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
2 bạn đã viết trước đó, đặt số lượng cho một mục mới thà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()
9 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

$ python optional_params.py
{'Bread': 1}
7 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 (

$ python optional_params.py
{'Bread': 1}
8). Đ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
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
2 để cả hai đối số là tùy chọn:

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
4

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

# 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 với một chuỗi trống làm khóa và giá trị là
# 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. 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:

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
5

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
{'Bread': 1}
1. Chuỗi trống có giá trị giả, có nghĩa là
# 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)
3 trả 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()
print(shopping_list)
4, 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):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item()
print(shopping_list)
5 đượ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):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item()
print(shopping_list)
5 sẽ giải thích những điều này là
# 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 hoặc
# 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)
4. 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):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item()
print(shopping_list)
3 returns
# 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)
4, whereas any other string will have a truthy value. When an
# 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)
5 keyword is followed by a truthy or falsy value, the
# 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)
5 statement will interpret these as
# 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 or
# 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)
4. 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):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item()
print(shopping_list)
5 để 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à

# 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. Đâ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
# 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 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à

# 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 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:

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
6

Bây giờ bạn có thể chuyể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()
8 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à
# 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 để 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
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'
5 để 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
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'
5 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:

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
7

Bạn cũng có thể thêm 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()
8 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("Bread", 1)
print(shopping_list)
6, 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:

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
8

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ị:

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
9

Bây giờ, bạn sẽ thêm một giá trị mặc định cho 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()
8 trong
$ python optional_params.py
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
2 để 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ờ:

def foo(a, b):
    return a - b
foo(2, 1)         # Returns 1
foo(a=2, b=1)     # Returns 1
foo(b=2, a=1)     # Returns -1
foo()             # Raises an error
0

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:

def foo(a, b):
    return a - b
foo(2, 1)         # Returns 1
foo(a=2, b=1)     # Returns 1
foo(b=2, a=1)     # Returns -1
foo()             # Raises an error
1

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
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
2 mà không có đối số tương ứng vớ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()
8. Đ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:

def foo(a, b):
    return a - b
foo(2, 1)         # Returns 1
foo(a=2, b=1)     # Returns 1
foo(b=2, a=1)     # Returns -1
foo()             # Raises an error
2

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

def foo(a, b):
    return a - b
foo(2, 1)         # Returns 1
foo(a=2, b=1)     # Returns 1
foo(b=2, a=1)     # Returns -1
foo()             # Raises an error
3

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
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee
2 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ố

# 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 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

# 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 đượ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ư

# 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, 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:

def foo(a, b):
    return a - b
foo(2, 1)         # Returns 1
foo(a=2, b=1)     # Returns 1
foo(b=2, a=1)     # Returns -1
foo()             # Raises an error
4

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):
    if item_name in shopping_list.keys():
        shopping_list[item_name] += quantity
    else:
        shopping_list[item_name] = quantity

add_item()
print(shopping_list)
5. Bạn không nên dựa vào bản chất giả 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()
3 mà thay vào đó kiểm tra rõ ràng rằng đối số là
# 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. Dựa vào thực tế là
# 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 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

# 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:

def foo(a, b):
    return a - b
foo(2, 1)         # Returns 1
foo(a=2, b=1)     # Returns 1
foo(b=2, a=1)     # Returns -1
foo()             # Raises an error
5

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 # 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 và # 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

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 = {
    "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 và
# 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. 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 = {
    "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 và
# 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 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:

>>>

def foo(a, b):
    return a - b
foo(2, 1)         # Returns 1
foo(a=2, b=1)     # Returns 1
foo(b=2, a=1)     # Returns -1
foo()             # Raises an error
6

Biến

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
18 trỏ 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
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
18 như một đối số cho
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
20, thì bạn sẽ chuyển một biến cho
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
20:

>>>

def foo(a, b):
    return a - b
foo(2, 1)         # Returns 1
foo(a=2, b=1)     # Returns 1
foo(b=2, a=1)     # Returns -1
foo()             # Raises an error
7

Biến

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
18 trỏ 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
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
18 như một đối số cho
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
20, thì bạn sẽ chuyển một biến cho
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
20:

>>>

def foo(a, b):
    return a - b
foo(2, 1)         # Returns 1
foo(a=2, b=1)     # Returns 1
foo(b=2, a=1)     # Returns -1
foo()             # Raises an error
8

Biến

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
18 trỏ 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
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
18 như một đối số cho
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
20, thì bạn sẽ chuyển một biến cho
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
20:

>>>

def foo(a, b):
    return a - b
foo(2, 1)         # Returns 1
foo(a=2, b=1)     # Returns 1
foo(b=2, a=1)     # Returns -1
foo()             # Raises an error
9

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

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
26) được sử dụng ngay lập tức trước một chuỗi, chẳng hạn như
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
18, 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ẻ.

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

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
20 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
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
20 với dấu ngoặc đơn trống và nó sẽ in một dòng trống.

Bây giờ bạn đã sẵn sàng để xác định các chức năng của riêng bạn chấp nhận một số lượng các đối số đầu vào. Hiện tại, bạn có thể đơn giản hóa

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
30 để chỉ chấp nhận tên của các mặt hàng bạn muốn trong danh sách mua sắm. Bạn sẽ đặt số lượng thà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()
9 cho mỗi mục. Sau đó, bạn sẽ quay lại bao gồm các đại lượng như là một phần của các đối số đầu vào trong phần tiếp theo.

Chữ ký chức năng bao gồm số lượng đối số đầu vào bằng cách 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()
5 trông như thế này:

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

Bạn thường thấy các chữ ký chức năng sử dụng tê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()
5 để thể hiện loại đối số tùy chọn này. Tuy nhiên, đây chỉ là một tên tham số. Không có gì đặc biệt về cái tê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()
5. Đó là
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
26 trước đó cung cấp cho tham số này các thuộc tính cụ thể của nó, mà bạn sẽ đọc dưới đây. Thông thường, tốt hơn là sử dụng tên tham số phù hợp với nhu cầu của bạn tốt nhất để làm cho mã dễ đọc hơn, như trong ví dụ dưới đây:

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

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

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
30 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:

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

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

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
37 bằng cách xem xét một ví dụ đơn giản hóa:

>>>

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

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

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
37 là một tuple. Do đó, tất cả các đối số bổ sung được gán thành các mục trong tuple
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
37. 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
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
30 ở trên, trong đó bạn đã lặp lại thông qua tuple
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
37 bằng cách sử dụng vòng lặp
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
42.

Đ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

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
43 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:

>>>

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

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

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
37 là một tuple. Do đó, tất cả các đối số bổ sung được gán thành các mục trong tuple
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
37. 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
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
30 ở trên, trong đó bạn đã lặp lại thông qua tuple
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
37 bằng cách sử dụng vòng lặp
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
42.

Đ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 >>> def func(*, name1, name2): ... print(name1, name2) ... >>> func() Traceback (most recent call last): File "", line 1, in func() TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2' >>> func("Fred", "Bob") Traceback (most recent call last): File "", line 1, in func("Fred", "Bob") TypeError: func() takes 0 positional arguments but 2 were given >>> func(name1="Fred", name2="Bob") Fred Bob 43 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:

>>>

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

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

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
37 là một tuple. Do đó, tất cả các đối số bổ sung được gán thành các mục trong tuple
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
37. 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
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
30 ở trên, trong đó bạn đã lặp lại thông qua tuple
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
37 bằng cách sử dụng vòng lặp
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
42.

>>>

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

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

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
37 là một tuple. Do đó, tất cả các đối số bổ sung được gán thành các mục trong tuple
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
37. 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
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
30 ở trên, trong đó bạn đã lặp lại thông qua tuple
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
37 bằng cách sử dụng vòng lặp
>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
42.

Đ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

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "", line 1, in 
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "", line 1, in 
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
43 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.

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

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 = {
    "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 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 = {
    "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, nhưng đối với hướng dẫn này, bạn có thể cho 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()
5 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 = {
    "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, mà bạn sẽ tìm hiểu trong phần sau.

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

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

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

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 = {
    "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

Để tìm hiểu thêm về

# 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 và
# 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ạn có thể đọc Python Args và Kwargs: Demystified, và bạn sẽ tìm thấy thêm chi tiết về các đối số từ khóa và không thay đổi trong các hàm và thứ tự có thể được sử dụng để xác định chức năng Python của riêng bạn.

Sự kết luận

Xác định chức năng của riêng bạn để tạo chương trình con khép kín là một trong những khối xây dựng chính khi viết mã. Các chức năng hữu ích và mạnh mẽ nhất là các chức năng thực hiện một nhiệm vụ rõ ràng và bạn có thể sử dụng một cách linh hoạt. Sử dụng các đối số tùy chọn là một kỹ thuật quan trọng để đạt được điều này.

Trong hướng dẫn này, bạn đã học đượ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 = {
        "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 và
    # 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
    # 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
    and
    # 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
  • 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

Một sự hiểu biết tốt về các đối số tùy chọn cũng sẽ giúp bạn sử dụng các chức năng trong thư viện tiêu chuẩn và trong các mô-đun bên thứ ba khác. Hiển thị tài liệu cho các chức năng này sẽ hiển thị cho bạn chữ ký chức năng mà bạn có thể xác định được đối số nào được yêu cầu, những chức năng nào là tùy chọn và cái nào là

# 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 hoặc
# 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.

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

Là từ khóa đối số python tùy chọn?

Bạn có thể gán một đối số tùy chọn bằng toán tử gán theo định nghĩa hàm hoặc sử dụng câu lệnh Python ** Kwargs. Có hai loại đối số Một hàm Python có thể chấp nhận: vị trí và tùy chọn. Đối số tùy chọn là các giá trị không cần được chỉ định cho một hàm được gọi.Optional arguments are values that do not need to be specified for a function to be called.

Đối số chỉ từ khóa trong Python là gì?

Các đối số chỉ có từ khóa là một thuộc tính khác của các hàm Python đã có sẵn kể từ Python 3.0.Các đối số này được chỉ định bằng điểm đánh dấu '*'.Họ nhắc người dùng nêu từ khóa được sử dụng trong hàm đã được xác định khi thực hiện cuộc gọi đến cùng một chức năng.another attribute of Python functions that have been available since Python 3.0. These arguments are specified using the '*' marker. They prompt the user to state the keyword used in the already defined function when making a call to the same function.

Sự khác biệt giữa đối số từ khóa và đối số mặc định trong Python là gì?

Các đối số từ khóa cho phép chúng tôi sử dụng bất kỳ thứ tự nào, trong khi các đối số mặc định hỗ trợ chúng tôi đối phó với sự vắng mặt của các giá trị.Và cuối cùng, trong Python, các lập luận tùy tiện có ích khi chúng ta không biết có bao nhiêu lập luận cần thiết trong chương trình tại thời điểm đó.. And finally, in Python, arbitrary arguments come in handy when we don't know how many arguments are needed in the program at that moment.

4 loại đối số trong Python là gì?

Trong Python, chúng ta có 4 loại đối số chức năng sau ...
Đối số mặc định ..
Đối số từ khóa (đối số được đặt tên).
Đối số vị trí ..
Các đối số tùy ý (đối số có độ dài thay đổi *args và ** kwargs).