Python is * args and ** kwargs what is that? How to use?

 

Source: Pexels

 

In programming, a function is life!

 

Using Python as a novice - whether it is new to programming, or who are familiar with another language - all need to learn whether the number of parameters in the function definition matches the number of arguments and want to convey.

This is the basis of knowledge - helps to understand the world.

 

However, access to the function definition * args and ** kwargs, makes beginners start to encounter psychological barrier.

 

In Python code often we see the two words args and kwargs, generally will be added in front of one or two asterisks.

 

Do not be tripping over these statements. In fact, these are not anything super special parameters, it is not strange, but programmers agreed variable name, args is an abbreviation arguments, showing the positional parameters; kwargs is an abbreviation of keyword arguments, expressed keyword arguments.

 

This is actually two forms of Python variable parameters, * args and ** kwargs must be placed in front of, because the front position parameters in keyword arguments.

 

Next, we will learn how to use them specifically.

 

Positional parameters vs keyword arguments

 

To learn what is * args and ** kwargs, we need to distinguish between the two concepts.

 

First of all, to distinguish the difference between positional parameters and keyword parameters. At its most basic function, make a matching game - parameter 1 and parameter matching, parameters and parameter 2 2 match, and so on.

 

def printThese(a,b,c):   print(a, "is stored in a")   print(b, "is stored in b")   print(c, "is stored inc")printThese(1,2,3)"""1 is stored in a2 is stored in b3 is stored in c"""

 

Three parameters are required, the lack of which would cause a fault.

 

def printThese(a,b,c):   print(a, "is stored in a")   print(b, "is stored in b")   print(c, "is stored inc")printThese(1,2)"""TypeError: printThese() missing 1 required positional argument: 'c'"""

 

The default value of the parameter is given a function definition, then this parameter will become optional.

 

def printThese(a,b,c=None):   print(a, "is stored in a")   print(b, "is stored in b")   print(c, "is stored inc")printThese(1,2)"""1 is stored in a2 is stored in bNone is stored in c"""

 

In addition, these optional parameters will be the choice of keywords, you can now call parameters specified function name and the corresponding map.

 

The three variables default value is set to None, and then see how the order without considering the situation map.

 

 

defprintThese(a=None,b=None,c=None):   print(a, "is stored in a")   print(b, "is stored in b")   print(c, "is stored inc")printThese(c=3, a=1)"""def printThese(a=None,b=None,c=None):   print(a, "is stored in a")   print(b, "is stored in b")   print(c, "is stored inc")printThese(c=3, a=1)"""1 is stored in aNone is stored in b3 is stored in c"""

 

Splat operator

 

Source: Pexels

 

From start to say I love the name of the operator to start - too ...... visualized. * Multiplication is often related to, but in Python, is twice the splat operator.

 

This operator is like a box. The operator extend - the splat corresponds JavaScript-- process can be seen as a domino open, forming a larger sequence, but need more powerful analogy splat.

 

利用以下例子更容易解释清楚。

a = [1,2,3]b = [*a,4,5,6]print(b) # [1,2,3,4,5,6]

 

在代码实例中,将a的内容移入(解包)到新列表b中。

 

如何使用*args和**kwargs

 

我们知道splat运算符解包多个值,并且知道函数参数有两种类型。若现在还未弄明白,那么可以将*args理解为变元的缩写,而**kwargs理解为关键字变元的缩写。

 

各参数用于解压其各自的变元类型,允许使用可变字长变元列表进行函数调用。例如,创建一个函数表示学生的考试分数。

def printScores(student,*scores):   print(f"Student Name:{student}")   for score in scores:     print(score)printScores("Jonathan",100, 95, 88, 92, 99)"""Student Name: Jonathan10095889299"""

 

噢,等等,我并未称呼其为*args?是的,“args”是一个标准化规范,但仍然只是一个名称。事实上,在*args中,唯一的星号是真正的参与者,创建了列表,其内容则是来自函数调用的位置参数(在这些定义变元后)。

 

这些理清楚之后,**kwargs就很容易理解了。名称并不重要,重要的是双星号创建了字典,其内容是关键字参数,来自函数调用(在这些定义变元后)。

 

为了更好地演示,我们创建一个函数,输出参加全国英语等级考试的人员名单。

def printPetNames(owner,**pets):   print(f"Owner Name:{owner}")   for pet,name in pets.items():      print(f"{pet}:{name}")printPetNames("Jonathan", dog="Brock",fish=["Larry", "Curly", "Moe"],turtle="Shelldon")"""Owner Name: Jonathandog: Brockfish: ['Larry', 'Curly', 'Moe']turtle: Shelldon"""

 

来源:Pexels

 

最后,再给大家提供一些额外的“知识福利”。

 

下面一些谏言可有助于大家规避常见的陷阱并扩展知识面。

 

·       利用*args和**kwargs作为标准化规范,把握好位置参数和关键字参数;

·       不能将**kwargs置于*args前,否则将产生错误;

·       清楚意识到关键字参数和**kwargs之间的冲突,该值本是传达**kwarg的意思,但是却不明就里的成为关键字参数的名称;

·       在函数调用时可以采用splat运算符。

发布了65 篇原创文章 · 获赞 0 · 访问量 561

Guess you like

Origin blog.csdn.net/weixin_46089319/article/details/104004259