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. luogu P1327 数列排序

    题目描述 给定一个数列{an},这个数列满足ai≠aj(i≠j),现在要求你把这个数列从小到大排序,每次允许你交换其中任意一对数,请问最少需要几次交换? 输入格式 第一行,正整数n (n<=10 ...

  2. iOS App Extension入门

    转自简书:http://www.jianshu.com/p/8cf08db29356   iOS 10推出了很多新功能,其中有几个高调的变化:通知栏更加实用,电话可以防骚扰,iMessage变得更加有 ...

  3. 一篇文章教你轻松使用fastjson

    前言 只有光头才能变强. 文本已收录至我的GitHub精选文章,欢迎Star:https://github.com/ZhongFuCheng3y/3y JSON相信大家对他也不陌生了,前后端交互中常常 ...

  4. nbuoj2786 玻璃球

    题目:http://www.nbuoj.com/v8.83/Problems/Problem.php?pid=2786 用2个玻璃球找到从一100层的大楼的某一层落下刚好会摔碎,如何制定最优策略? 别 ...

  5. (全国多校重现赛一)A-Big Binary Tree

    You are given a complete binary tree with n nodes. The root node is numbered 1, and node x's father ...

  6. 《Dotnet9》系列-开源C# Winform控件库1《HZHControls》强力推荐

    大家好,我是Dotnet9小编,一个从事dotnet开发8年+的程序员.我最近在写dotnet分享文章,希望能让更多人看到dotnet的发展,了解更多dotnet技术,帮助dotnet程序员应用dot ...

  7. HTML中用AJAX方式把数据存储到浏览器中并取出

    把对象只有转成字符串形式才可以存入,取出则是把字符串转成对象

  8. 从零开始的openGL——五、光线追踪

    前言 前面介绍了基本图形.模型.曲线的绘制,但是,在好像还没有感受到那种3D游戏里一些能惊艳到自己的效果,即真实感还不是很足.这篇文章中介绍的光线追踪,是实现真实感必不可少的.拿下面的两张图片来对比 ...

  9. Java中通过代码得到int类型数值的二进制形式

    一.完整代码 public class BigInteger { int sing; byte[] val; public BigInteger(int val){ // 将传递的初始值,按位取值,存 ...

  10. 【Selenium】自动进入网页,出现弹窗被卡住

    问题现象: 使用命令:driver.get("http://127.0.0.1/zentao/user-login.html") 进入网页,出现如下弹窗,无法进入 解决方法: #d ...