Python function parameters matching model (on)

Outline

Python3 the function parameters are generally passed through the assignment, but the caller only needs to know how to properly transfer function parameters can be used directly,

Positional parameters

That we are the most frequently used method of parameter passing, by matching the default location parameters from left to right

def f(x, y, z):
    print(x, y, z)


f(1, 2, 3)
复制代码

Sample results:

1 2 3
复制代码

Keywords parameters

We can pass arguments keyword arguments passed, this time passing parameters by matching variable name, but not the way the position of the match, so we use hybrid location-based parameters and parameter passing keyword-based principle is first match based on the parameters from left to right position, and then in match keyword-based variable names.

def f(x, y, z):
    print(x, y, z)


# 关键字匹配
f(x=1, y=2, z=3)
# 无需位置的匹配
f(y=2, z=3, x=1)
# 位置与关键字的混合匹配
f(1, z=3, y=2)
复制代码

Sample results:

1 2 3
1 2 3
1 2 3
复制代码

The default parameters

When we pass parameters, default parameters are always some time, that is, if no incoming value, then, before it is executed, these parameters are given a default value, which is why we often use parameter is defined in the function definition

def f(x, y=2, z=3):
    print(x, y, z)


# 仅传递非默认参数
f(1)
# 同样可以进行位置参数的传递
f(1, 2, 3)
# 传递关键字参数
f(1, y=4, z=5)
复制代码

Sample results:

1 2 3
1 2 3
1 4 5
复制代码

Reproduced in: https: //juejin.im/post/5cfa5ca6f265da1b725bf425

Guess you like

Origin blog.csdn.net/weixin_34152820/article/details/91436794