Preface
Hello everyone, today we will talk about two very powerful features in Python:*args
and**kwargs
. These two things often appear in function definitions, but many beginners do not understand them in depth enough. Today we will thoroughly understand their usage and differences, so that you can be more handy when writing code!
1. What are *args and kwargs? **
*args
and**kwargs
They are two special syntaxes used in Python for function definition, mainly used to handle variable number of parameters. Their names don't matter (you can replace them with other names), but they are usually used*args
and**kwargs
。
-
*args
: Used for deliveryVariable number of non-keyword parameters(Positional parameters). -
**kwargs
: Used for deliveryVariable number of keyword parameters(key value pair parameters).
2. How to use args
*args
Allows you to pass any number of non-keyword parameters to the function. These parameters will be packaged into oneTuple (tuple), can be passed inside the functionargs
Come visit.
2.1 Basic usage
def my_function(*args): for arg in args: print(arg) my_function(1, 2, 3)
Output:
1
2
3
2.2 Use with other parameters
*args
Can be used with other parameters, but must be placed inAfter the positional parameters。
def my_function(a, b, *args): print("a:", a) print("b:", b) print("args:", args) my_function(1, 2, 3, 4, 5)
Output:
a: 1
b: 2
args: (3, 4, 5)
3. How to use kwargs
**kwargs
Allows you to pass any number of keyword parameters to the function. These parameters will be packaged into oneDictionary (dict), can be passed inside the functionkwargs
Come visit.
3.1 Basic usage
def my_function(**kwargs): for key, value in (): print(f"{key}: {value}") my_function(name="Alice", age=25, city="Beijing")
Output:
name: Alice
age: 25
city: Beijing
3.2 Use with other parameters
**kwargs
Can be used with other parameters, but must be placed inAfter positional parameters and *args。
def my_function(a, b, *args, **kwargs): print("a:", a) print("b:", b) print("args:", args) print("kwargs:", kwargs) my_function(1, 2, 3, 4, name="Alice", age=25)
Output:
a: 1
b: 2
args: (3, 4)
kwargs: {'name': 'Alice', 'age': 25}
4. The difference between *args and kwargs**
characteristic | *args | **kwargs |
---|---|---|
Parameter Type | Non-keyword parameters (positional parameters) | Keyword parameters (key value pair parameters) |
Packaging form | Package into tuples | Package into a dictionary (dict) |
Use scenarios | Handle an uncertain number of position parameters | Handle an uncertain number of keyword parameters |
Function Calls | func(1, 2, 3) |
func(name="Alice", age=25) |
Function definition | def func(*args): |
def func(**kwargs): |
5. Practical application scenarios
5.1 Function Decorator
When writing a decorator,*args
and**kwargs
Very useful because they can handle any number and type of parameters.
def my_decorator(func): def wrapper(*args, **kwargs): print("Before function call") result = func(*args, **kwargs) print("After function call") return result return wrapper @my_decorator def my_function(a, b): return a + b print(my_function(1, 2))
Output:
Before function call
After function call
3
5.2 Inheritance and rewrite
In the inheritance of the class,*args
and**kwargs
Can be used to pass parameters of the parent class.
class Parent: def __init__(self, name): = name class Child(Parent): def __init__(self, age, *args, **kwargs): super().__init__(*args, **kwargs) = age child = Child(age=10, name="Alice") print(, )
Output:
Alice 10
6. Things to note
-
Naming Specifications:
-
*args
and**kwargs
It is a conventional naming method, but you can use other names, such as*numbers
or**options
。
-
-
Sequence question:
- In the function definition,
*args
Must be placed after positional parameters,**kwargs
Must be placed*args
after.
- In the function definition,
-
Flexibility and readability:
- Although
*args
and**kwargs
Very flexible, but overuse may reduce the readability of the code. It is recommended to use when it is clear that variable quantity parameters need to be processed.
- Although
7. Summary
-
*args
Used to handle variable number of non-keyword parameters, packaged into tuples. -
**kwargs
Used to process variable number of keyword parameters, packaged into dictionary. - The two can be used in combination, but must follow the order: Positional Parameters ->
*args
->**kwargs
。
master*args
and**kwargs
The usage method allows you to write more flexible and powerful Python code.
This is the article about the usage and differences between args and kwargs in Python. This is all about this article. For more related content on the usage of args and kwargs in Python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!