Skip to content

[Python] Tutorial(8) function, default , *args, **kwargs

Last Updated on 2021-04-09 by Clay

The previous tutorial teach how to create a basically function. Today I note a skill I rarely to use, the value we will give function: default, *args, **kwargs.

The explanation part will a bit in my way, I guess you go trying more different code, don't care about my nonsense. Hahahahaha.


default

The meaning of "default", is the default input we will give the function. If we don't give function any value when we call it, the function will use the default value we set.

We get to see a simple example:

def test(n, a=1, b=2):
    print(n+a+b)


And then we use the function "test" we defined.

test(1, 2, 3)


Output:

6

This is a very simple function. Maybe you're skilled for this.

And the next question. Where is the "default" I say?

test(1)


Like this, yes! We just only input an only argument for it! The other arguments we not give, the function will fill in automatically according to the default value!

Output:

4

1 + 1 + 2 = 4 —— It's no problem!


*args

And, what is the argument "*args".

That looks strange, I know.

Intuitively, it can mean "arguments input without a limited number".

Let's go!

def test(n, *args):
    a = n
    for arg in args:
        a += arg
   
    print(a)


We set two input arguments to input.

test(1, 2, 3, 4, 5, 6)


Output:

21

1 + 2 + 3 + 4 + 5 + 6 = 21 !

That's right! Except that 1 us a variable, the others all are *args input value!

In this way, you understand of what I mean by "arguments input without a limited length"?


**kwargs

Finally, finally we come to the highlight of today —— **kwargs!

Compared with *args, we must add the variable name when we inputting the arguments to function.

So that we can correctly distinguish which argument belong **kwargs.

Incidentally, in the composition rules of function, *args must be placed before **kwargs, so that our program's Parser will not mistake the syntax we entered.

Let's looking at the example:

def test(n, **kwargs):
    print(n)
    for a, b in kwargs.items():
        print(a, b)


We can see, that "**kwargs" has something like a type dict.

So as I said, we have to specify the value we want to input.

test(1, key=3, value=9)


Output:

1
key 3
value 9

So, do you all know more about it?

When I was learning Python, I was so lucky to see and learn the code developed by master. They always use *args, **kwargs ..... simple.

After a long time afterwards, I finally realized what the code at the time was writing!

From the basic tutorial of Python that I designed to write, the lass of the content is less than eight times! Gradually getting closer to the follow-up teaching I want to write is getting closer!

I still have the idea of sharing some knowledge of everyone.

I hope that the day when I can write an advanced teaching course will come soon.


References


Read More

Leave a ReplyCancel reply

Exit mobile version