I think the reason why we feel useless is that we often fall into a thinking situation:
The person who wrote function and the person who uses function are the same person, that is me
Because if the writer and user are the same person, then of course you can be very free in designing the interface. You can choose * or use list directly.
But today when we use other people’s APIs or write functions for others to use, we don’t have that much flexibility
At this time, * can help us a lot
These two things are quite useful!
Give me some examples
When used for function arguments
Suppose there is a function intro:
def intro(name, age, city, language):
print('I am {}. I am {} years old. I live in {}. I love {}'.format(
name, age, city, language
))
Today I will give you a set of list data lst 和 dict 的 data dic:
One is that Python does not allow multiple loads, so you cannot use the same function name
But * can solve this problem:
def add(*n):
return sum(n)
Of course, you may think that I can also design the parameters here to be list or tuple, but sometimes this approach is more convenient. You can refer to the concept of print (Python3):
Supplement
I think the reason why we feel useless is that we often fall into a thinking situation:
Because if the writer and user are the same person, then of course you can be very free in designing the interface. You can choose
*
or use list directly.But today when we use other people’s APIs or write functions for others to use, we don’t have that much flexibility
At this time,
*
can help us a lotThese two things are quite useful!
Give me some examples
When used for function arguments
Suppose there is a function
intro
:Today I will give you a set of list data
lst
和 dict 的 datadic
:No need for
*
或**
or**
You may want to:Use
*
和**
and**
:When used for function params
Today we are going to write an addition function:
If you want to expand to multiply three numbers:
There are two questions here:
One is that the parameter list may be very long
One is that Python does not allow multiple loads, so you cannot use the same function name
But
*
can solve this problem:Of course, you may think that I can also design the parameters here to be list or tuple, but sometimes this approach is more convenient. You can refer to the concept of
print
(Python3):That’s the concept here
Secondly, this approach is the basis for writing decorator:
Because if you don’t use this approach, you can’t deal with the various parameters of the function you want to modify
When used for tuple unpacking (Python3)
This function is very useful:
Conclusion
In fact, there are more wonderful things than these, just waiting for you to discover!
Questions I answered: Python-QA