欢迎光临
我们一直在努力

Advanced Knowledge of Function in Python

  •   The overall introduction is here
  • Introduction to Python

In the previous chapter we know some basic knowledge of python function. Python function is actually an Object, so there are rich features of function.

1. Positional and Keyword Parameters

1.1 basic

In the previois chapter we saw an example

def add(a, b):
return a + b

add(1, 2)

As we can see, the parameters are positional-based. When we use the function, the reference of the first argument will be copied and assigned to a, the second one will be assigned to b. In detailed, 1 is assigned to a, and 2 is assigned to b.

This kind of passing arguments is simple yet difficult to remember. Sometimes we have functions that contain more than 10 parameters. In this case, it's difficult for us to remember the position and order of parameters. So key-word parameter comes.

def add(a, b):
return a + b

add(add1 = 1, add2 = 2)
add(add2 = 2, add1 = 1)

The definition of function doesn't change.

1.2 Seporator

Sometimes we want to use positional and keyword arguments at the same time. We can use * seporator to declare them.

def avearge(a, b, *, c, d):
return (a+b+c+d)/4

#Arguments before * are positional and arguments after * are keyword-based

average(1, 2, c = 3, d = 4)

1.3 Collection

Sometimes we need to pass indefined number of parameters. 

We can use *args to collect positional arguments and **kwargs to collect keyword-based arguments.

def my_function(a, b, *args, c, d, **kwargs):
print(a, b, args, c, d, **kwargs)

my_function(1, 2, 3, 4, c = 5, d = 6, e = 7, f = 8)

#output
1 2 [3, 4] 5 6 {"e":7, "f":8}

The first part=============> a, b, *args
| | |
| | |
1 2 [3, 4]

The second part============> c, d, **kwargs
| | |
| | |
5 6 {"e":7, "f":8}

1, 2, 3, 4 are positional arguments. c = 5, d = 6, e = 7, f = 8 are keyword-based arguments.

a is assigned 1, b is assigned 2, 3 and 4 are collected into args in the form of list. c is assigned 5, d is assigned 6, e and f are collected into kwargs in the form of dictionary.

We haven't learned about list and dictionary, so just remember the form. 

2. Default Parameters

We can use default parameters in function. Default parameters means that the parameter has a default value. When you use the function and do not pass the argument, the interpreter will use the default value.

def add(a, b = 1):
return a + b

add(1, 2) # return 3
add(1) # return 2

Easy, right?

However, there is a small trap here, about passing default list. We will talk about it later.

赞(0)
未经允许不得转载:171主机测评 » Advanced Knowledge of Function in Python
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址