笔记-python-tutorial-4.controlflow( and function)
1. 函数
1.1. 定义函数
def name(x):
“””函数的第一行语句可以是可选的字符串文本,即函数的文档字符串,或docstring”””
if x>= 0:
return x
空函数
def nop():
pass
函数引用的实际参数在函数调用时引入局部符号表,实参总是传值调用
函数可返回多个值,但实际返回的是一个tuple
2、 默认参数值
def ask_ok(promt,retries=4,complaint=’yes or no.’)
3、 引用
如果函数保存到.py文件中,使用
from file_name import func_name()
来导入函数,注意文件名不包括.py
2. 函数相关
2.1. 函数参数
1.位置参数
2.default argument values:
def ask_ok(prompt, retries = 4, reminder=’Please try again!’):
注意:默认参数的值仅在编译时确认一次,此后不在修改
i = 5
def f(arg=i):
print(arg)
i = 6
f() #print 5
这在默认参数引用空表时会导致结果异常
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
This will print
[1]
[1, 2]
[1, 2, 3]
解决办法是
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
3.keyword argument:
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
注意关键字参数必需跟在位置参数后面;
4.可变参数: *argv
定义可变参数和定义一个list或tuple参数相比,仅仅在参数前面加了一个*号。在函数内部,参数numbers接收到的是一个tuple,因此,函数代码完全不变。但是,调用该函数时,可以传入任意个参数,包括0个参数:
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
calc(*nums)
5.unpacking argument lists
>>> list(range(3, 6)) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args)) # call with arguments unpacked from a list
[3, 4, 5]
有点像指针,第2个函数调用时,如果不使用*,range得到的是一个数组,需要将这个数组分解为2 个参数再传递给range()。
类似的,使用**也可以解包dictionaries形式的参数。
>>> def parrot(voltage, state='a stiff', action='voom'):
... print("-- This parrot wouldn't", action, end=' ')
... print("if you put", voltage, "volts through it.", end=' ')
... print("E's", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
2.2. lambda expressions
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
make返回的是一个函数,因此f是一个函数。
>>> f
<function make_incrementor.<locals>.<lambda> at 0x0000006D285F2E18>
>>> f(4)
46
尽量少这么写,写多了总会坑人的。
2.3. document strings
常用案例:
>>> def my_function():
... """Do nothing, but document it.
...
... No, really, it doesn't do anything.
... """
... pass
...
>>> print(my_function.__doc__)
Do nothing, but document it.
No, really, it doesn't do anything.
2.4. function annotations
函数注释,没搞太明白。
>>> def f(ham: str, eggs: str = 'eggs') -> str:
... print("Annotations:", f.__annotations__)
... print("Arguments:", ham, eggs)
... return ham + ' and ' + eggs
...
>>> f('spam')
Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
Arguments: spam eggs