python的函数,,By francis


By francis_haoOct 31,2018

官方的函数定义(BNF语法标记)

技术分享图片

decorator

decorator仅仅是一个语法糖,函数可以使用它被封装起来,其返回值必须是可执行的,decorator语法在定义的时候会被执行。在下例中

@ff
deffunc():pass

等同于

deffunc():pass
func = ff(func)

ff可以是一个函数或者一个类,详见参考【3】。在定义时,ff(func)会被执行,ff(func)的返回值必须是可执行的。

parameter list

参数类型有三类:可赋值参数、元组参数和字典参数

可赋值参数可以设置默认值,之后在调用函数的时候可以省略该参数。如果一个参数设置了默认值,那么其后的可赋值参数也必须设置默认值。

元组参数的形式为"*[parameter]", "*parameter"作用是通过元组接收多余的位置参数,如果省略了parameter,将不接收多余的位置参数("*"的由来见参考【5】),在"*"或"*parameter"后的参数只能是关键字参数,通过关键字传值进去

字典参数的形式为"**parameter",作用是通过字典接收多余的关键字参数,此项都是放在参数列表的最后

annotation

有两种形式,一种用于函数参数(上面三种参数均可),用":"标识,另一种用于整个函数,用"->"标识。annotation可以是任何的python表达式。

示例

1、decorator

### decorator
print("------ decorator ------")
defff(fc):
print("in ff and arg is {}".format(fc))
return fc
@ff
deffunc_decor():
print("in function func_decor")
print("---------------")
func_decor()

输出结果

技术分享图片

2、parameter list

### parameter
print("\n------ parameter ------")
deffunc_param1(a, b,*c,**d):
print(a)
print(b)
print(c)
print(d)

func_param1(1,2,3,4, excess=1)

print("---------------")
deffunc_param2(a=1, b=2,*, c=4,**d):
print(a)
print(b)
print(c)
print(d)

func_param2(1,2,excess=1)

输出结果

技术分享图片

"*"的错误使用示例

a、

deffunc_param2(a=1, b=2,*, c=4,**d):
print(a)
print(b)
print(c)
print(d)

func_param2(1,2,3,excess=1)

输出结果如下,"*"不接收多余的位置参数,如果传入多余的参数会抛异常,详见参考【5】

技术分享图片

b、

deffunc_param3(a=1, b=2,*,**d):
print(a)
print(b)
print(d)

func_param3()

输出结果如下,"*"后面如果有参数,其后的第一个参数必须是关键字参数

技术分享图片

3、annotation

### annotation
print("\n------ annotation ------")
deffunc_annot(a:print("parameter a"))->print("return annotation"):
print("in func_annot : test annotation")
print("---------------")
func_annot(1)

输出结果

技术分享图片

技术分享图片
本文由 刘英皓 创作,采用 知识共享署名-非商业性使用-相同方式共享3.0中国大陆许可协议 进行许可。欢迎转载,请注明出处:
转载自:https://www.cnblogs.com/yinghao1991/p/9886360.html

参考

【1】Function definitions https://docs.python.org/3.8/reference/compound_stmts.html#function-definitions

【2】A guide to Python‘s function decorators https://www.thecodeship.com/patterns/guide-to-python-function-decorators/

【3】Decorators I: Introduction to Python Decorators https://www.artima.com/weblogs/viewpost.jsp?thread=240808

【4】https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters

【5】PEP 3102 -- Keyword-Only Arguments https://www.python.org/dev/peps/pep-3102/

python的函数

评论关闭