Article Directory
Two types of parameters in the function 1. Python
We know that there are two parameters in Python
- Location parameters (positional argument): positional parameters can only be determined by the parameter position
- Keyword parameters (keyword argument): Method keyword parameters only need to pass the keyword = somekey reference
Positional parameters can only be determined by the parameter position. It also determines 位置参数一定要在前面
otherwise, the number of keyword parameters will change so that the position can not judge.
2. Understand the function call*
*
The role of the tuple or list elements in the unpack, passed separately, as a plurality of parameters.
def func(a,b,c)
print(a,b,c)
alist = [1,2,3] # 这里alist的长度必须和函数中参数的个数相同,否则会报错
func(*alist) # 等同于 func(1, 2, 3)
1 2 3
2.1 *
did
It apart columns alist
value as a 位置参数
, and the position of these parameters to the function func
to call.
So split the number of columns, setter position parameters mean func(*alist)
and func(1,2,3)
are equivalent because alist= [1,2,3]
.
3. Understand the function call**
**
Unpack the role of the dictionary, and the dictionary data items as parameters to the function keys.
To better understand a few examples:
def func(a, b, c):
print(a, b, c)
if __name__ == "__main__":
dic = {'b': 2, 'c': 3}
func(1, b=2, c=3)
func(1, **dic)
1 2 3
1 2 3
4. appreciated that the function call *args
, and**kwargs
kwargs
Is keyword argument
the abbreviation, args
that is argument
. Common *args
in **kwargs
front.
And the use of these two effects as follows:
def this_fun(a,b,*args,**kwargs):
"""
在这个函数定义中,参数”a, b”代表”常规参数列表”。
args 接收元组作为位置参数,而非是常见的参数列表
"""
print(a,b)
print(args)
print(kwargs)
if __name__ = '__main__'
this_fun(0,1,2,3,index1=11,index2=22)
0,1
(2, 3)
{'index2': 22, 'index1': 11}
In other words, the first parameter in uncertain form the rest of the no keyword parameters close together to form a tuple, while the second has to make it up a keyword dictionary.
The examples illustrate args
, kwargs
the application scenario
5.1 subclass parameter passing to the parent class method
At any time the derived class and override the methods we should use args
, kwargs
received positional parameters and key parameters to the parent class method. By way of example we better understand
class Model(object):
def __init__(self, name):
self.name = name
def save(self, force_update=False, force_insert=False):
if force_update and force_insert:
raise ValueError("Cannot perform both operations")
if force_update:
print("Updated an existing record")
if force_insert:
print("Created a new record")
The definition of a class, we can create an object class, object class has a method save()
. Object assume that the class can be save()
saved to the database method. By function save()
parameters to decide whether to create a record or update an existing record in the database.
We construct a new class, class of Model
behavior, but only to meet certain conditions will not save objects of this class. This new class inherits Model
, rewrite Model
thesave()
class ChildModel(Model):
def save(self, *args, **kwargs):
if self.name == 'abcd':
super(ChildModel, self).save(*args, **kwargs)
else:
return None
Actually occurs in the corresponding storage operation 'Model' in the save
process. So we call the subclass save()
method rather than the 'Model' approach. Subclass ChildModel
of save()
receiving any parent class save () required parameters, and passed to the parent class method. Thus, the subclass save()
method has the argument list *args
and **kwargs
which may receive any parameter or key-location parameters, except general parameters list.
Creating ChildModel entity below and call the save method:
c=ChildModel('abcd')
c.save(force_insert=True)
c.save(force_update=True)
# 结果
Created a new record
Updated an existing record
Here transmission parameter save () method to the object. Call is save subclass (), which receives a parameter containing the keyword kwargs
dictionary. It then uses **
the dictionary as keyword arguments unpack, and then passes it to the superclass save()
. Therefore, the superclass save()
get keyword parameters force_insert
and perform the appropriate action.
5.2 * args achieve sum
def my_sum(*args):
res = 0
for val in args:
res += val
return res
l1 = [4, 8]
l2 = [1,2,3]
print(my_sum(*l1)) # 12
print(my_sum(*l2)) # 6
print(my_sum(4,5,6)) # 15