Basic syntax

函数定义

首先看一个函数的基本语法

def func_name(arguments):
    print("Your name is " + arguments)
    return 0

第一行:首先用def声明要定义一个函数,然后定义函数名称func_name,括号里面是用来定义函数的接收参数,最后跟上一个:

第二行:函数体,函数体就是函数的逻辑,也就是这个函数要干什么事

第三行:通过return来退出函数,并且返回一些返回值,当然,函数也可以没有返回值

函数调用

调用上一个func_name函数

>>> def func_name(arguments):
...     print("Your name is " + arguments)
...     return 0
... 
>>> 
>>> func_name('Da')
Your name is Da
0

函数参数

可变参数

可变参数,也被人叫做非命名可变参数,首先它是不支持命名的,同时它是可变的不收数量限制的,通常用*args表示,*args在接受到参数内容时,它会自动创建元组来存放接收到的数据

def sum(*args):
    ret = 0
    print(args)
    for x in args:
        ret += x
    print(ret)

sum(1, 2, 3, 4, 5)
(1, 2, 3, 4, 5)
15

可变关键字参数

可变关键字,也被人称之为命名可变参数,首先它支持针对参数值命名,同时跟可变参数一样支持不限量的参数,**kwargs,它会自动创建字典来存放接收到的数据

def print_info(**kwargs):
    print(kwargs)
    for k, v in kwargs.items():
        print('Key: {0}  Value: {1}'.format(k, v))

print_info(a=1, b=2)
{'a': 1, 'b': 2}
Key: a  Value: 1
Key: b  Value: 2

可变位置参数和可变关键字可以混合使用

虽然两者可以混用,不过可变位置参数需要在可变关键字前面,而且传递数据时顺序一定要写对

def mix(*args, **kwargs):
    for i in args:
        print('第{0}个'.format(i))
    for k, v in kwargs.items():
        print('Key: {0}  Value: {1}'.format(k, v))

mix(1, 2, 3, 4, 5, a=1, b=2, c=3)
1个
第2个
第3个
第4个
第5个
Key: b  Value: 2
Key: c  Value: 3
Key: a  Value: 1

默认参数、可变位置参数、可变关键字参数可以混合使用

def mix(x, y, *args, **kwargs):
    print('x: {}'.format(x))
    print('y: {}'.format(y))
    for i in args:
        print('第{0}个位置参数'.format(i))
    for k, v in kwargs.items():
        print('Key: {0}  Value: {1}'.format(k, v))

mix(1, 2, 3, 4, 5, a=1, b=2, c=3)
x: 1
y: 23个位置参数
第4个位置参数
第5个位置参数
Key: b  Value: 2
Key: c  Value: 3
Key: a  Value: 1

参数解包

def add(x, y):
    print('x is {}'.format(x))
    print('y is {}'.format(y))
    return x + y

lst = [1, 2]
dct = {'x': 1, 'y': 2}

print('# 普通解包')
print(add(lst[0], lst[1]))
print('# list解包')
print(add(*lst))
print('# dict解包')
print(add(**dct))

效果是一样的,通过*lst或者**dct完成参数解包,更加简洁

# 普通解包
x is 1
y is 2
3
# list解包
x is 1
y is 2
3
# dict解包
x is 1
y is 2
3

坑一

In[2]: def fn(lst=[]):
    lst.append(1)
    print(lst)

In[3]: fn()
[1]
In[4]: fn()
[1, 1]
In[5]: fn()
[1, 1, 1]

def fn(lst=[]) 等同于在函数外 lst=[],所以才会发生上面的情况

解法

In[7]: def fn():
...     lst=[]
...     lst.append(1)
...     print(lst)

In[8]: fn()
[1]
In[9]: fn()
[1]

或者

In[13]: def fn(lst = None):
    if lst is None:
        lst = []
    lst.append(1)
    print(lst)

In[14]: fn()
[1]
In[15]: fn()
[1]
In[16]: fn()
[1]

函数参数总结

  • 可变参数在位置参数之后
  • 默认参数在其他参数之后
  • 可变关键字参数
  • 越简单越好,混用太多,最后恶心的是自己

results matching ""

    No results matching ""