网站建设还流行吗,仿素材下载网站源码,做旅游网站需要引进哪些技术人才,wordpress开发服务一、装饰器概述装饰器允许开发者在不修改原函数代码的情况下#xff0c;给函数添加额外的功能装饰器本质上是一个返回函数的高阶函数在 Python 中#xff0c;使用装饰器语法糖 可以便捷应用装饰器二、函数概念
1、函数是一等对象
函数可以赋值给变量
def greet(name):return…一、装饰器概述装饰器允许开发者在不修改原函数代码的情况下给函数添加额外的功能装饰器本质上是一个返回函数的高阶函数在 Python 中使用装饰器语法糖可以便捷应用装饰器二、函数概念1、函数是一等对象函数可以赋值给变量defgreet(name):returnfHello,{name}my_funcgreetprint(my_func(Alice))# 输出结果 Hello, Alice函数可以作为参数传递defgreet(name):print(fHello,{name})defcall_twice(func,arg):greet(arg)greet(arg)call_twice(greet,Alice)# 输出结果 Hello, Alice Hello, Alice可以定义在另一个函数内部defcall_twice(arg):defgreet(name):returnfHello,{name}print(greet(arg) greet(arg))call_twice(Alice)# 输出结果 Hello, Alice Hello, Alice函数可以作为返回值defget_func(flag):defadd(num1,num2):returnnum1num2defsubtract(num1,num2):returnnum1-num2ifflag:returnaddelifflag-:returnsubtract result_funcget_func()resultresult_func(10,20)print(result)# 输出结果 302、闭包闭包是嵌套函数中内部函数引用外部函数的变量即使外部函数已经执行完毕如下例函数 inner_func 引用了外部函数的变量 x即使函数 outer_func 已经执行完函数 closure 仍能访问 xdefouter_func(x):definner_func(y):returnxyreturninner_func closureouter_func(10)resultclosure(5)print(result)# 输出结果 15三、装饰器手动实现基本实现# 装饰器函数defmy_decorator(func):defwrapper():print(函数执行前)resultfunc()print(函数执行后)returnresultreturnwrapper# 原始函数defsay_hello():print(Hello)# 应用装饰器decorated_say_hellomy_decorator(say_hello)decorated_say_hello()# 输出结果 函数执行前 Hello 函数执行后函数带参数# 装饰器函数defmy_decorator(func):defwrapper(**kwargs):print(函数执行前)resultfunc(**kwargs)print(函数执行后)returnresultreturnwrapper# 原始函数defsay_hello(name):print(fHello,{name})# 应用装饰器decorated_say_hellomy_decorator(say_hello)decorated_say_hello(nameAlice)# 输出结果 函数执行前 Hello, Alice 函数执行后装饰器带参数# 装饰器函数defmy_decorator(func,times):defwrapper():print(函数执行前)foriinrange(times):func()print(函数执行后)returnwrapper# 原始函数defsay_hello():print(Hello World)# 应用装饰器decorated_say_hellomy_decorator(say_hello,3)decorated_say_hello()# 输出结果 函数执行前 Hello World Hello World Hello World 函数执行后四、装饰器语法糖实现基本实现# 装饰器函数defmy_decorator(func):defwrapper():print(函数执行前)resultfunc()print(函数执行后)returnresultreturnwrapper# 应用装饰器my_decoratordefsay_hello():print(Hello)say_hello()# 输出结果 函数执行前 Hello 函数执行后函数带参数# 装饰器函数defmy_decorator(func):defwrapper(**kwargs):print(函数执行前)resultfunc(**kwargs)print(函数执行后)returnresultreturnwrapper# 应用装饰器my_decoratordefsay_hello(name):print(fHello,{name})say_hello(nameAlice)# 输出结果 函数执行前 Hello, Alice 函数执行后装饰器带参数# 装饰器函数defmy_decorator(times):defdecorator(func):defwrapper():print(函数执行前)foriinrange(times):func()print(函数执行后)returnwrapperreturndecorator# 应用装饰器my_decorator(times3)defsay_hello():print(Hello World)say_hello()# 输出结果 函数执行前 Hello World Hello World Hello World 函数执行后