函数 -> 装饰器

函数的4个核心概念

1.函数可以赋与变量

def func(message):print('Got a message: {}'.format(message))send_message = func
send_message('hello world')
#输出
#Got a message: hello world

2.函数可以当作函数的参数

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 寻找有志同道合的小伙伴,
互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
def get_message(message):return 'Got a message: ' + messagedef root_call(func, message):print(func(message))root_call(get_message, 'hello world')
输出
#Got a message: hello world

3.函数里嵌套函数

def func(message):def get_message(message):print('Got a message: {}'.format(message))return get_message(message)func('hello world')
输出
#Got a message: hello world

4.函数作为函数返回值(闭包)

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 寻找有志同道合的小伙伴,
互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
def func_closure():def get_message(message):print('Got a message: {}'.format(message))return get_messagesend_message = func_closure()
send_message('hello world')
#输出
#Got a message: hello world

简单装饰器

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 寻找有志同道合的小伙伴,
互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
def my_decorator(func):def wrapper():print('wrapper of decorator')func()return wrapperdef greet():print('hello world')greet = my_decorator(greet)
greet()

使用语法糖 @

def my_decorator(func):def wrapper():print('wrapper of decorator')func()return wrapper@my_decorator
def greet():print('hello world')greet()
# 输出
# wrapper of decorator
# hello world

带有参数的装饰器

直接在 wrapper函数中加上参数

def my_decorator(func):def wrapper(message):print('wrapper of decorator')func(message)return wrapper@my_decorator #相当于 greet == wrapper(message)
def greet(message):print(message)greet('hello world')
# 输出
#wrapper of decorator
#hello world

这个装饰器只能用在有一个参数的函数,如果想对任意参数的函数通用,可以这么写

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 寻找有志同道合的小伙伴,
互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
def my_decorator(func):def wrapper(*args, **kwargs):print('wrapper of decorator')func(*args, **kwargs)return wrapper

带自定义参数的装饰器

利用装饰器自定义参数这特性,实现重复执行装饰器内部函数

def repeat(num):def my_decorator(func):def wrapper(*args, **kwargs):for i in range(num):print('wrapper of decorator')func(*args, **kwargs)return wrapperreturn my_decorator@repeat(4)
def greet(message):print(message)greet('hello world')# 输出:
# wrapper of decorator
# hello world
# wrapper of decorator
# hello world
# wrapper of decorator
# hello world
# wrapper of decorator
# hello world

原函数还是原函数?

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 寻找有志同道合的小伙伴,
互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
greet.__name__
#输出
'wrapper'help(greet)
# 输出
Help on function wrapper in module __main__:wrapper(*args, **kwargs)

可以看出,原函数的原信息会被wrapper取代

如果不想其改变,那么可用内置装饰器@functools.wraps将原函数的元信息拷贝过去。

import functoolsdef my_decorator(func):@functools.wraps(func)def wrapper(*args, **kwargs):print('wrapper of decorator')func(*args, **kwargs)return wrapper@my_decorator
def greet(message):print(message)greet.__name__# 输出
#'greet'

类装饰器

类装饰器主要依赖于 call()函数,每当调用类实例时,call()函数会被执行一次

class Count:def __init__(self, func):self.func = funcself.num_calls = 0def __call__(self, *args, **kwargs):self.num_calls += 1print('num of calls is: {}'.format(self.num_calls))return self.func(*args, **kwargs)@Count
def example():print("hello world")example()# 输出
# num of calls is: 1
# hello worldexample()# 输出
# num of calls is: 2
# hello world

装饰器的嵌套

@decorator1
@decorator2
@decorator3
def func():...
#相当于 decorator1(decorator2(decorator3(func)))
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 寻找有志同道合的小伙伴,
互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import functoolsdef my_decorator1(func):@functools.wraps(func)def wrapper(*args, **kwargs):print('execute decorator1')func(*args, **kwargs)return wrapperdef my_decorator2(func):@functools.wraps(func)def wrapper(*args, **kwargs):print('execute decorator2')func(*args, **kwargs)return wrapper@my_decorator1
@my_decorator2
def greet(message):print(message)greet('hello world')# 输出
# execute decorator1
# execute decorator2
# hello world

装饰器的实例用法

1)身份验证,不登录不允许操作

import functoolsdef authenticate(func):@functools.wraps(func)def wrapper(*args, **kwargs):request = args[0]if check_user_logged_in(request): # 如果用户处于登录状态return func(*args, **kwargs) # 执行函数 post_comment()else:raise Exception('Authentication failed')return wrapper@authenticate
def post_comment(request, ...)...

2)日志记录 可测试函数的执行时间

import time
import functoolsdef log_execution_time(func):def wrapper(*args, **kwargs):start = time.perf_counter()res = func(*args, **kwargs)end = time.perf_counter()print('{} took {} ms'.format(func.__name__, (end - start) * 1000))return resreturn wrapper@log_execution_time
def calculate_similarity(items):...
  1. 合法性检测
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 寻找有志同道合的小伙伴,
互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import functoolsdef validation_check(input):@functools.wraps(func)def wrapper(*args, **kwargs):... # 检查输入是否合法@validation_check
def neural_network_training(param1, param2, ...):...LRU cache. @lru_cache缓存装饰器
@lru_cache
def check(param1, param2, ...) # 检查用户设备类型,版本号等等...
  1. try…excaption
class ServerDebugHelper:@classmethoddef debug(cls):def decorator(func):@wraps(func)def wrapper(*args, **kwargs):try:return func(*args, **kwargs)except:import tracebackprint(traceback.format_exc())return wrapperreturn decorator

Python进阶: Decorator 装饰器你太美相关推荐

  1. python进阶20装饰器

    原创博客地址:python进阶20装饰器 Nested functions Python允许创建嵌套函数,这意味着我们可以在函数内声明函数并且所有的作用域和声明周期规则也同样适用. 1 2 3 4 5 ...

  2. python中的装饰器decorator

    python中的装饰器 装饰器是为了解决以下描述的问题而产生的方法 我们在已有的函数代码的基础上,想要动态的为这个函数增加功能而又不改变原函数的代码 例如有三个函数: def f1(x):return ...

  3. Python中的decorator装饰器使用方法

    装饰器的运用是Python编程中的一项高级技巧,这里由浅入深,整理了12步入门Python中的decorator装饰器使用方法,需要的朋友可以参考下 装饰器(decorator)是一种高级Python ...

  4. Python 中的闭包、匿名函数、decorator 装饰器与python的偏函数

    Python中的闭包 def calc_sum(lst):def lazy_sum():return sum(lst)return lazy_sum 像这种内层函数引用了外层函数的变量(参数也算变量) ...

  5. python高级语法装饰器_Python高级编程——装饰器Decorator超详细讲解上

    Python高级编程--装饰器Decorator超详细讲解(上篇) 送你小心心记得关注我哦!! 进入正文 全文摘要 装饰器decorator,是python语言的重要特性,我们平时都会遇到,无论是面向 ...

  6. python装饰器类-PYTHON里的装饰器能装饰类吗

    扩展回答 如何理解python里的装饰器 通常可以理解它是一个hook 的回调函数. 或者是理解成python 留给二次开发的一个内置API. 一般是用回调和hook 方式实现的. 如何理解Pytho ...

  7. Python学习之==装饰器

    在Python中,装饰器和迭代器.生成器都是非常重要的高级函数. 在讲装饰器之前,我们先要学习以下三个内容: 一.函数的作用域 1.作用域介绍 Python中的作用域分为四种情况: L:local,局 ...

  8. python 进阶:修饰器的介绍

    参考链接:Python 函数装饰器 我认为python中的装饰器是一个很厉害的功能,他能瞬间提升代码的逼格,但对于我这样的小白来说,别说为所欲为的使用了,就连简单的尝试一下,却也是难于登天.经过长达半 ...

  9. python装饰器原理-python 中的装饰器及其原理

    装饰器模式 此前的文章中我们介绍过装饰器模式: 装饰器模式中具体的 Decorator 实现类通过将对组建的请求转发给被装饰的对象,并在转发前后执行一些额外的动作来修改原有的部分行为,实现增强 Com ...

最新文章

  1. SSM项目的数据库密码加密方案
  2. matlab多边形扫描线填充算法代码,计算机图形学—多边形扫描与填充
  3. N35-第九周作业-张同学
  4. 使用机器学习检测TLS 恶意加密流——业界调研***有开源的数据集,包括恶意证书的,以及恶意tls pcap报文***...
  5. python time localtimeq获取准确时间_Python时间模块datetime、time、calendar的使用方法
  6. python新手入门英文词汇笔记(1-1)_Python新手入门英文词汇(1-1)
  7. 专升本c语言网课听谁的好_都说塑钢泥比玻璃胶好,填缝永不变黑,师傅却说不好用,听谁的?...
  8. 【CSS】font样式简写(转)- 不是很建议简写
  9. Word2vec学习笔记总结
  10. springboot+flowable第四节(设置监听事件)
  11. window系统电脑进入bios设置的万能通用方法,台式组装机也可以使用。
  12. element-ui下拉框全选
  13. php 阿里云 批量 单个 发送短信 (拿来即用)
  14. 0-glusterfs: failed to set volfile server: File exists
  15. 三菱M80操作介绍_三菱PLC电脑上仿真操作步骤
  16. 内部稽核与内部控制管理体系关系的探讨
  17. mysql如何查看事务日记_Mysql事务和Mysql 日志
  18. Oracle 字段自增
  19. Bearer Token的相关定义与使用方法
  20. 软件借用RSA增加注册功能

热门文章

  1. redis简单了解 二 (集群)
  2. UIColor之【扩展:#FFFFFF -UIColor】
  3. Nutch爬虫解决页面相对路径问题
  4. spoj 8222 Substrings (后缀自动机)
  5. Happy new year 2009
  6. 【学习笔记】ODATA
  7. 在Dialog中实现下拉框效果并对下拉框赋自定义的值
  8. SAP-FICO-AR-关于剩余支付和部分支付的区别
  9. 释疑の作业分割的理解
  10. 究竟是“二O一六年”还是“二零一六年”?嘴上会说可你会写吗?