*和**为可变形参,但是平时在使用的时候感觉很少能有使用到的情况,有些不是很理解它们的用法和用处场景?
而且形参不是可以传递任意类型么?这样我写成:
a = (1,2,3,4)
def test(a):
print a
print a[1]
加不加*貌似没什么区别?字典也是一样只不过变成print['keyname']而已。
那么*和**这玩意到底有什么用呢?
巴扎黑2017-04-18 09:17:29
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
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
:
lst = ['dokelung', 27, 'Taipei', 'Python']
dic = {'name': 'dokelung', 'age': 27, 'city': 'Taipei', 'language': 'Python'}
No need for *
或 **
or **
You may want to:
test(lst[0], lst[1], lst[2], lst[3])
test(dic['name'], dic['age'], dic['city'], dic['language'])
Use *
和 **
and **
:
test(*lst)
test(**dic)
Today we are going to write an addition function:
def add2(a, b):
return a + b
If you want to expand to multiply three numbers:
def add3(a, b, c):
return a + b + c
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:
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):
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
^^^^^^^^
That’s the concept here
Secondly, this approach is the basis for writing decorator:
def mydeco(func):
def newfunc(*args, **kwargs):
return func(*args, **kwargs)
return newfunc
Because if you don’t use this approach, you can’t deal with the various parameters of the function you want to modify
This function is very useful:
>>> t = ('start', 1 ,2 ,3 ,4 ,5, 'end')
>>> s, *nums, e = t
>>> s, nums, e
('start', [1, 2, 3, 4, 5], 'end')
In fact, there are more wonderful things than these, just waiting for you to discover!
Questions I answered: Python-QA