【Python】函数

定义函数

>>> def fib(n):    # write Fibonacci series up to n
...     """Print a Fibonacci series up to n."""
...     a, b = 0, 1
...     while a < n:
...         print(a, end=' ')
...         a, b = b, a+b
...     print()
...
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

第一条语句是文档字符串,要有编写这个的好习惯

变量引用首先局部符号表中查找,然后外层函数的局部符号表最后内置名称表

除非是 global 或者 nonlocal

没有指定返回值则返回 None

函数的其他定义形式

默认值

参数默认值在后续调用会共享

def f(a, L=[]):
    L.append(a)
    return L
 
print(f(1))
print(f(2))
print(f(3))

将输出

[1]
[1, 2]
[1, 2, 3]

任意参数列表

>>> def concat(*args, sep="/"):
...     return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'

解包

>>> args = [3, 6]
>>> list(range(*args)) # 解包列表
[3, 4, 5]

>>> 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 !

函数标注

函数标注是关于用户自定义函数中使用的类型的完全可选元数据信息

函数标注以字典的形式存放在函数的 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
'spam and eggs'
posted @ 2020-08-30 20:44  宇NotNull  阅读(161)  评论(0编辑  收藏  举报