Detailed explanation of Python function parameter passing mechanism

Public number: You Er Hut
Author: Peter
Editor: Peter

Hello everyone, my name is Peter~

Wrote the functionality of a Python function recently and made some mistakes. This article mainly sorts out the parameter passing mechanism of Python functions. The main contents include:

1. The simplest function (no return value, parameter)

def hello_python():
    print("hello python!")
复制代码
hello_python()  # 直接调用
复制代码
hello python!
复制代码

Second, the simplest function (with return value, no parameters)

def hello_python():
    data = "hello python!"
    return data  # data就是返回值
复制代码
hello_python()
复制代码
'hello python!'
复制代码

3. With one parameter (no default value)

def hello(data):
    result = "hello " + data 
    return result
复制代码
hello("python")
复制代码
'hello python'
复制代码

Pass in another value:

hello("java")
复制代码
'hello java'
复制代码

It is also possible to modify the information of the parameter internally:

def hello_name(name):
    result = "Hello " + name.title() + "!"
    return result
复制代码
hello_name("tom")
复制代码
'Hello Tom!'
复制代码
hello_name("jack")
复制代码
'Hello Jack!'
复制代码

Fourth, with multiple parameters (no default value)

def information(name, age):
    data = "我叫" + name.title() + ", 今年" + str(age) + "岁"
    return data
复制代码
information("tom", 23)
复制代码
'我叫Tom, 今年23岁'
复制代码
information("JACK", 18)
复制代码
'我叫Jack, 今年18岁'
复制代码

5. Parameter setting default value (one parameter)

def hello_name(name="Peter"):
    result = "Hello " + name
    return result
复制代码

If no specific value is given for the parameter, the default value is used

hello_name()  
复制代码
'Hello Peter'
复制代码

Give the parameter an actual value, such as Tom is the actual value in the following example; this is often referred to as an actual parameter

hello_name(name="Tom")  
复制代码
'Hello Tom'
复制代码

6. Parameter setting default value (multiple parameters)

def information(name="Peter", age=20):
    data = "我是" + name + ", 今年" + str(age) + "岁"
    return data
复制代码

1. All default values ​​are used:

information()
复制代码
'我是Peter, 今年20岁'
复制代码

2. All incoming actual values:

information(name="Tom", age=27)
复制代码
'我是Tom, 今年27岁'
复制代码

3. Only the actual values ​​of some parameters are passed in; the default values ​​are used for those not passed in:

information(name="Tom")
复制代码
'我是Tom, 今年20岁'
复制代码
information(age=18)
复制代码
'我是Peter, 今年18岁'
复制代码

7. Some parameters use default values

Parameters with default values ​​must be placed last; parameters with default values ​​must be placed last

def information(name, age=20):
    data = "我是" + name + ", 今年" + str(age) + "岁"
    return data
复制代码
information("Peter")  # age默认使用20
复制代码
'我是Peter, 今年20岁'
复制代码
information(name="Peter")
复制代码
'我是Peter, 今年20岁'
复制代码
information("Peter", age=18)
复制代码
'我是Peter, 今年18岁'
复制代码

The following method directly reports an error:

information(age=18, "Peter")  
复制代码
  File "<ipython-input-26-2d03cd04a05a>", line 1
    information(age=18, "Peter")
                       ^
SyntaxError: positional argument follows keyword argument
复制代码
information(age=18, name="Peter")  # age默认使用20
复制代码
'我是Peter, 今年18岁'
复制代码

Important: In a function, you must list parameters without default values ​​first, and then list parameters with default values:

def information(age=20, name):
    data = "我是" + name + ", 今年" + str(age) + "岁"
    return data
复制代码
  File "<ipython-input-28-d36363c3194c>", line 1
    def information(age=20, name):
                   ^
SyntaxError: non-default argument follows default argument
复制代码

How to understand that parameters with default values ​​must be placed at the end?

The following is a custom function of get_name, passing in the first, last and middle names, but not everyone has a middle name:

def get_name(first_name, last_name, middle_name=''):
    if middle_name:  # 如果存在中间名字
        name = first_name + middle_name + last_name
    else:
        name = first_name + last_name
        
    return name
复制代码
get_name(first_name="张", last_name="飞", middle_name='')
复制代码
'张飞'
复制代码
get_name(first_name="孙", last_name="空", middle_name='悟')
复制代码
'孙悟空'
复制代码

The result of not passing middle_name is definitely not what we want:

get_name(first_name="孙", last_name="空")
复制代码
'孙空'
复制代码

Eight, location parameters

def get_information(name, age):
    data = "我是" + name + ", 今年" + str(age) + "岁"
    return data
复制代码
get_information("Tom", 20)
复制代码
'我是Tom, 今年20岁'
复制代码
get_information("20","Tom")  # 一定要按照原来形参的顺序传递
复制代码
'我是20, 今年Tom岁'
复制代码

The above result is definitely not what we want

Nine, keyword arguments

When passing arguments by keyword, the order is irrelevant:

get_information(name="Tom", age=20)
复制代码
'我是Tom, 今年20岁'
复制代码
get_information(age=20, name="Tom")
复制代码
'我是Tom, 今年20岁'
复制代码

10. Mixed use of positional arguments and keyword arguments

get_information("Tom", age=20)
复制代码
'我是Tom, 今年20岁'
复制代码

When using it, you still need to follow the order in the original function, otherwise an error will be reported:

get_information(age=20,"Tom")
复制代码
  File "<ipython-input-39-bc20bc544493>", line 1
    get_information(age=20,"Tom")
                          ^
SyntaxError: positional argument follows keyword argument
复制代码

Eleven, advanced: *args use

Sometimes our implementation does not know how many parameters the function needs to accept. At this time, we can collect any number of parameters through the usage of *argsor .**kwargs

The use introduced first *args. Suppose we want to convert the height of each student in a class into meters, that is, divide by 100:

def height(*args):
    data = args 
    return data
复制代码
height()
复制代码

By default the function collects an empty tuple:

()
复制代码
height(178)
复制代码

When passing in data, it is represented in the form of a tuple:

(178,)
复制代码
height(178,189)
复制代码
(178, 189)
复制代码
def height(*args):
    for data in args:  # 对args中的元素进行循环操作
        print("身高是: {}m".format(data / 100))
复制代码
height(189,180,167,172)  # 调用
复制代码
身高是: 1.89m
身高是: 1.8m
身高是: 1.67m
身高是: 1.72m
复制代码

12. Advanced: use **kwargs

**kwargs允许将不定长度的键值对,作为参数传递给一个函数

def information(**kwargs):
    data = kwargs
    print(data)
复制代码

默认情况下收集的是字典:

 information(name="Peter")
复制代码
{'name': 'Peter'}
复制代码
information(name="Peter", age=23)
复制代码
{'name': 'Peter', 'age': 23}
复制代码
def information(**kwargs):
    for k, v in kwargs.items():
        print("{0} == {1}".format(k,v))
复制代码
information(name="Peter")
复制代码
name == Peter
复制代码
information(name="Peter", age=23)
复制代码
name == Peter
age == 23
复制代码
information(name="Peter", age=23, height=175)
复制代码
name == Peter
age == 23
height == 175
复制代码

十三、进阶:*args 和形参连用

def fun(x, *args):
    print("x:", x)
    print("args:", args)
复制代码
fun(1)
复制代码
x: 1
args: ()
复制代码
fun(1,2)
复制代码
x: 1
args: (2,)
复制代码
fun(1,2,3,4)
复制代码
x: 1
args: (2, 3, 4)
复制代码
fun(1,2,3,4,"Peter")
复制代码
x: 1
args: (2, 3, 4, 'Peter')
复制代码

十四、进阶:**kwargs 和形参连用

def fun(x, **kwargs):
    print("x:", x)
    print("kwargs:", kwargs)
复制代码
fun(1)
复制代码
x: 1
kwargs: {}
复制代码
fun(1,name="Peter")
复制代码
x: 1
kwargs: {'name': 'Peter'}
复制代码
fun(1,name="Peter",age=23)
复制代码
x: 1
kwargs: {'name': 'Peter', 'age': 23}
复制代码

十五、进阶:形参+*args+**kwargs连用

def fun(x, *args, **kwargs):
    print("x:", x)
    print("args:", args)
    print("kwargs:", kwargs)
复制代码
fun(1)
复制代码
x: 1
args: ()
kwargs: {}
复制代码
fun(1,2,3)
复制代码
x: 1
args: (2, 3)
kwargs: {}
复制代码
fun(1,name="Peter",age=23)
复制代码
x: 1
args: ()
kwargs: {'name': 'Peter', 'age': 23}
复制代码
fun(1,2,3,name="Peter",age=23)
复制代码
x: 1
args: (2, 3)
kwargs: {'name': 'Peter', 'age': 23}
复制代码
kwargs = {"name":"Peter","age":23}

fun(1,2,3,**kwargs)
复制代码
x: 1
args: (2, 3)
kwargs: {'name': 'Peter', 'age': 23}
复制代码

推荐资料

最后给大家推荐一个来自B站的波波老师讲解的关于Python函数的内容,感兴趣可以去观看,讲解的很详细:

www.bilibili.com/video/BV1At…

Guess you like

Origin juejin.im/post/7119152018932891656