python 装饰器使用总结

by:授客 QQ1033553122

测试环境

win10

python 3.5

例1:一个简单的例子

#!/usr/bin/env python

# -*- coding:utf-8 -*-

 

__author__ = 'shouke'

 

def wrapper_method1(func):# func用于接收被装饰的函数地址

    def wrapper():

print("执行wrapper_method1")

func()#调用被装饰的函数

    return wrapper#返回方法地址,供执行被装饰函数前调用

@wrapper_method1#等同于wrapper_method1(myfunction)

def myfuntion():

print("执行myfunction")

myfuntion()

运行结果:

执行wrapper_method1

执行myfunction

例2:装饰带参数函数

#!/usr/bin/env python

# -*- coding:utf-8 -*-

 

__author__ = 'shouke'

 

def wrapper_method1(func):

    def wrapper(name, age):#这里的参数列表和myfuntion参数列表保持一致

print("执行wrapper_method1 name:%s age:%s" % (name, age))

func(name, age)#记得给要调用的函数传递参数

    return wrapper

@wrapper_method1

def myfuntion(name, age):

print("执行myfunction name:%s age:%s" % (name, age))

myfuntion('shouke', 'unknow')

运行结果:

执行wrapper_method1 name:shouke age:unknow

执行myfunction name:shouke age:unknow

#!/usr/bin/env python

# -*- coding:utf-8 -*-

 

__author__ = 'shouke'

 

def wrapper_method1(func):

    def wrapper(*args, **kwargs):

print("执行wrapper_method1 args:", args)

func(*args, **kwargs)

    return wrapper

@wrapper_method1

def myfuntion(*args,**kwargs):

print("执行myfunction args:", args)

myfuntion('shouke', 'unknow')

运行结果:

执行wrapper_method1 args: ('shouke', 'unknow')

执行myfunction args: ('shouke', 'unknow')

例3:函数被多给装饰器方法装饰

#!/usr/bin/env python

# -*- coding:utf-8 -*-

 

__author__ = 'shouke'

 

def wrapper_method1(func):

    def wrapper(*args, **kwargs):

print("执行wrapper_method1")

func(*args, **kwargs)

    return wrapper

def wrapper_method2(func):

    def wrapper():

print("执行wrapper_method2")

func()

    return wrapper

@wrapper_method1

@wrapper_method2

def myfuntion():

print("执行myfunction")

myfuntion()

运行结果:

执行wrapper_method1

执行wrapper_method2

执行myfunction

说明:装饰器方法执行顺序为从远到近,从上到下。

例4:在类中使用装饰器

#!/usr/bin/env python

# -*- coding:utf-8 -*-

 

__author__ = 'shouke'

 

def wrapper_method1(func):

    def wrapper(*args, **kwargs):

print("执行wrapper_method1")

func(*args, **kwargs)

    return wrapper

class MyClass:

    def __init__(self):

    pass

 

 

@staticmethod

@wrapper_method1

    def myfuntion():

print("执行myfunction")

MyClass.myfuntion()

运行结果:

执行wrapper_method1

执行myfunction

例5:装饰器方法也可以是类函数

#!/usr/bin/env python

# -*- coding:utf-8 -*-

 

__author__ = 'shouke'

 

class MyClass2:

@staticmethod

        def wrapper_method1(func):

        def wrapper(*args, **kwargs):

print("执行wrapper_method1")

func(*args, **kwargs)

    return wrapper

class MyClass:

    def __init__(self):

        pass

 

@staticmethod

@MyClass2.wrapper_method1

    def myfuntion():

print("执行myfunction")

MyClass.myfuntion()

运行结果:

执行wrapper_method1

执行myfunction

需要注意的点

1、 即便被装饰函数拥有默认值也要显示传递参数,否则报错,如下:

#!/usr/bin/env python

# -*- coding:utf-8 -*-

 

__author__ = 'shouke'

 

def wrapper_method1(func):

    def wrapper(name, age):

print("执行wrapper_method1 name:%s age:%s" % (name, age))

func(name, age)

    return wrapper

@wrapper_method1

def myfuntion(name='shouke', age='unknow'):

print("执行myfunction name:%s age:%s" % (name, age))

myfuntion()

运行结果:

TypeError: wrapper() missing 2 required positional arguments: 'name' and 'age'

2、 如果被装饰函数为类的静态函数时,@staticmethod必须位于最上方,否则报错,如下:

#!/usr/bin/env python

# -*- coding:utf-8 -*-

 

__author__ = 'shouke'

 

def wrapper_method1(func):

    def wrapper(*args, **kwargs):

print("执行wrapper_method1")

func(*args, **kwargs)

    return wrapper

 

class MyClass:

    def __init__(self):

        pass

 

@wrapper_method1

@staticmethod

    def myfuntion():

print("执行myfunction")

MyClass.myfuntion()

运行结果:

Traceback (most recent call last):

执行wrapper_method1

File "E:/PrivateReops/CassTestManage/TMP/backend/mytest.py", line 34, in <module>

MyClass.myfuntion()

File "E:/PrivateReops/CassTestManage/TMP/backend/mytest.py", line 9, in wrapper

func(*args, **kwargs)

TypeError: 'staticmethod' object is not callable

python 装饰器使用总结的更多相关文章

  1. 关于python装饰器

    关于python装饰器,不是系统的介绍,只是说一下某些问题 1 首先了解变量作用于非常重要 2 其次要了解闭包 def logger(func): def inner(*args, **kwargs) ...

  2. python装饰器通俗易懂的解释!

    1.python装饰器 刚刚接触python的装饰器,简直懵逼了,直接不懂什么意思啊有木有,自己都忘了走了多少遍Debug,查了多少遍资料,猜有点点开始明白了.总结了一下解释得比较好的,通俗易懂的来说 ...

  3. Python 装饰器学习

    Python装饰器学习(九步入门)   这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方式. 第一步:最简单的函数,准备附加额外功能 1 2 3 4 5 6 7 8 # -*- c ...

  4. python 装饰器修改调整函数参数

    简单记录一下利用python装饰器来调整函数的方法.现在有个需求:参数line范围为1-16,要求把9-16的范围转化为1-8,即9对应1,10对应2,...,16对应8. 下面是例子: def fo ...

  5. python 装饰器学习(decorator)

    最近看到有个装饰器的例子,没看懂, #!/usr/bin/python class decorator(object): def __init__(self,f): print "initi ...

  6. Python装饰器详解

    python中的装饰器是一个用得非常多的东西,我们可以把一些特定的方法.通用的方法写成一个个装饰器,这就为调用这些方法提供一个非常大的便利,如此提高我们代码的可读性以及简洁性,以及可扩展性. 在学习p ...

  7. 关于python装饰器(Decorators)最底层理解的一句话

    一个decorator只是一个带有一个函数作为参数并返回一个替换函数的闭包. http://www.xxx.com/html/2016/pythonhexinbiancheng_0718/1044.h ...

  8. Python装饰器由浅入深

    装饰器的功能在很多语言中都有,名字也不尽相同,其实它体现的是一种设计模式,强调的是开放封闭原则,更多的用于后期功能升级而不是编写新的代码.装饰器不光能装饰函数,也能装饰其他的对象,比如类,但通常,我们 ...

  9. Python装饰器与面向切面编程

    今天来讨论一下装饰器.装饰器是一个很著名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志.性能测试.事务处理等.装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量函数中与函数 ...

  10. python装饰器方法

    前几天向几位新同事介绍项目,被问起了@login_required的实现,我说这是django框架提供的装饰器方法,验证用户是否登录,只要这样用就行了,因为自己不熟,并没有做过多解释. 今天查看dja ...

随机推荐

  1. react-native测试安装

    !!!注意!!!:init命令默认会创建最新的版本,而目前最新的0.45及以上版本需要下载boost等几个第三方库编译.这些库在国内即便翻墙也很难下载成功,导致很多人无法运行iOS项目!!!中文网在论 ...

  2. Vue - 简单实现一个命令式弹窗组件

    前言 在日常工作中弹窗组件是很常用的组件,但用得多还是别人的,空闲时间就自己来简单实现一个弹窗组件 涉及知识点:extend.$mount.$el 使用方式: this.$Confirm({ titl ...

  3. 【Flutter】372- Flutter移动端实战手册

    ☝点击上方蓝字,关注我们! 本文字数:3705字 预计阅读时间:28分钟 导 读 Flutter又双叒叕来了!本周推送是我们Flutter系列文章的最终篇!<Flutter移动端实战手册> ...

  4. 【CentOS7】常用命令

    [CentOS7]常用命令 转载:https://www.cnblogs.com/yangchongxing/p/10646640.html 目录 ========================== ...

  5. vivado三人表决仿真

    概述 下面以三人表决电路的verilog仿真来了解一下vivado软件的使用. 编写设计文件 首先可以在开始的界面通过create new project来新建工程,也可以通过file-->pr ...

  6. 3步轻松搞定Spring Boot缓存

    作者:谭朝红 前言 本次内容主要介绍基于Ehcache 3.0来快速实现Spring Boot应用程序的数据缓存功能.在Spring Boot应用程序中,我们可以通过Spring Caching来快速 ...

  7. java获取每月的第一天和最后一天

    // 获取当前年份.月份.日期 Calendar cale = null; cale = Calendar.getInstance(); // 获取当月第一天和最后一天 SimpleDateForma ...

  8. netty用法总结

    /**decoder和encoder,如果不需要解析,就使用系统的 * ch.pipeline().addLast(new StringDecoder()); * ch.pipeline().addL ...

  9. JavaScript原型 补充

    js原型 // 构造函数 = 类 function A(){} let a1 = new A(); // 添加原型 num => 类似于属性 A.prototype.num = 100; con ...

  10. diff命令的妙用

    在读<Writing compilers and Interpreters>一书时需要按章节修改代码,由于实在一行一行比对实在难受,于是想了个办法,利用diff命令比较两章之间代码的修改位 ...