装饰器:在某个方法执行前后去执行其他新定义的行为

例如:

#!/usr/bin/env python
# _*_ coding:UTF-8 _*_

def before_say_hello():
    print "before hello"

def after_say_hello():
    print "after hello"

def say_hello_wrapper(func):
    def wrapper():
        print "Before"
        before_say_hello()
        func()
        print "After"
        after_say_hello()
    return wrapper

@say_hello_wrapper
def say_hello():
    print "Hello!"

if __name__ == "__main__":
    say_hello()

执行结果:

/Users/liudaoqiang/PycharmProjects/numpy/venv/bin/python /Users/liudaoqiang/Project/python_project/day14/decorator_test.py
Before
before hello
Hello!
After
after hello

Process finished with exit code 0

2.装饰器的执行步骤

(1)首先,装饰器本身也是一个函数,即say_hello_wrapper也是一个函数,也需要在执行前加入到内存

(2)当执行到@say_hello_wrapper时,即将say_hello()替换为say_hello_wrapper()里面的wrapper(), 即为相同的内存地址

(3)当执行到say_hello()时,则会执行say_hello_wrapper()

注意:使用debug模式可知装饰器的执行步骤

3. 带参数函数的装饰器

#!/usr/bin/env python
# _*_ coding:UTF-8 _*_

def before_say_hello():
    print "before hello"

def after_say_hello():
    print "after hello"

def say_hello_wrapper(func):
    def wrapper(content):
        print "Before"
        before_say_hello()
        func(content)
        print "After"
        after_say_hello()
    return wrapper

@say_hello_wrapper
def say_hello(content):
    print "Hello, {0}".format(content)

if __name__ == "__main__":
    say_hello("World")

结果:

/Users/liudaoqiang/PycharmProjects/numpy/venv/bin/python /Users/liudaoqiang/Project/python_project/day14/decorator_test.py
Before
before hello
Hello, World
After
after hello

Process finished with exit code 0

注意:只需将参数加入到wrapper()中即可,因为wrapper()为替换函数

4.带返回值函数的装饰器

#!/usr/bin/env python
# _*_ coding:UTF-8 _*_

def before_say_hello():
    print "before hello"

def after_say_hello():
    print "after hello"

def say_hello_wrapper(func):
    def wrapper(content):
        print "Before"
        before_say_hello()
        ret = func(content)
        print "After"
        after_say_hello()
        return ret
    return wrapper

@say_hello_wrapper
def say_hello(content):
    print "Hello, {0}".format(content)
    return content

if __name__ == "__main__":
    ret = say_hello("World")
    print ret

结果:

/Users/liudaoqiang/PycharmProjects/numpy/venv/bin/python /Users/liudaoqiang/Project/python_project/day14/decorator_test.py
Before
before hello
Hello, World
After
after hello
World

Process finished with exit code 0

老男孩python学习自修第十七天【装饰器】的更多相关文章

  1. 老男孩python学习自修第十八天【面向对象】

    1.类与对象(构造方法与实例化) #!/usr/bin/env python # _*_ coding:UTF-8 _*_ class Province: def __init__(self, nam ...

  2. python学习笔记(5)--迭代器,生成器,装饰器,常用模块,序列化

    生成器 在Python中,一边循环一边计算的机制,称为生成器:generator. 如: >>> g = (x * x for xin range(10)) >>> ...

  3. python学习笔记-(八)装饰器、生成器&迭代器

    本节课程内容概览: 1.装饰器 2.列表生成式&迭代器&生成器 3.json&pickle数据序列化 1. 装饰器 1.1 定义: 本质上是个函数,功能是装饰其他函数—就是为其 ...

  4. python学习之路 六 :装饰器

    本节重点: 掌握装饰器相关知识 ​ python装饰器就是用于拓展原来函数功能的一种函数,这个函数的特殊之处在于它的返回值也是一个函数,使用python装饰器的好处就是在不用更改原函数的代码前提下给函 ...

  5. python学习总结---函数使用 and 装饰器

    # 函数使用 ### 零碎知识 - 灵活的if-else ```python a = 3 if False else 5 print(a) ''' if False: a = 3 else: a = ...

  6. Python学习日记(七)——装饰器

    1.必备知识 #### 一 #### def foo(): print 'foo' foo #表示是函数 foo() #表示执行foo函数 #### 二 #### def foo(): print ' ...

  7. Python学习基础(三)——装饰器,列表生成器,斐波那契数列

    装饰器——闭包 # 装饰器 闭包 ''' 如果一个内部函数对外部(非全局)的变量进行了引用,那么内部函数被认为是闭包 闭包 = 函数块 + 定义时的函数环境 ''' def f(): x = 100 ...

  8. Python学习笔记(yield与装饰器)

    yeild:返回一个生成器对象: 装饰器:本身是一个函数,函数目的装饰其他函数(调用其他函数) 功能:增强被装饰函数的功能 装饰器一般接受一个函数对象作为参数,以便对其增强 @原函数名  来调用其他函 ...

  9. 老男孩python学习自修第二十四天【多进程】

    1. 体验多进程的运行速度 #!/usr/bin/env python # _*_ coding:UTF-8 _*_ from multiprocessing import Pool import t ...

随机推荐

  1. Thymeleaf3语法详解

    每天学习一点点 编程PDF电子书.视频教程免费下载:http://www.shitanlife.com/code   Thymeleaf是Spring boot推荐使用的模版引擎,除此之外常见的还有F ...

  2. P2080 增进感情(背包DP)

    思路:将好感度x+y作为体积, 幸福度x-y作为作为价值, 然后就是一个经典的背包问题了.emmmmm,还可以特判一下,因为幸福度为0时就是最小了,没有必要看后面的了吧. 其实,我自己做的时候,沙雕的 ...

  3. php微信生成微信公众号二维码扫描进入公众号带参数

    https://blog.csdn.net/qq_22823581/article/details/80248555 <?php namespace app\api\model; set_tim ...

  4. (二 -5) 天猫精灵接入Home Assistant-自动发现Mqtt设备--电风扇

    官网:https://www.home-assistant.io/components/fan.mqtt/ 1 添加配置文件 要在安装中启用MQTT风扇,请将以下内容添加到您的configuratio ...

  5. KindEditor 开源得富文本编辑器

    正常HTML情况写输入长文本需要textarea 标签 .但textarea 标签局限性很大,切只能输入单一的文本,我们大多情况下看到的新闻类文本信息大多是图文混排得,且有的配有视频和音乐. 我们可以 ...

  6. 通过buildroot+qemu搭建ARM-Linux虚拟开发环境

    1. 配置工作环境 sudo apt install gcc build-essential bison flex gettext tcl sharutils libncurses-dev zlib1 ...

  7. Numpy求均值、中位数、众数的方法

    首先需要数据源,这里随便写了一个: nums = [1,2,3,4] 求均值和中位数均可以使用numpy库的方法: import numpy as np #均值 np.mean(nums) #中位数 ...

  8. Spring Cloud (十四):Spring Cloud 开源软件都有哪些?

    学习一门新的技术如果有优秀的开源项目,对初学者的学习将会是事半功倍,通过研究和学习优秀的开源项目,可以快速的了解此技术的相关应用场景和应用示例,参考优秀开源项目会降低将此技术引入到项目中的成本.为此抽 ...

  9. 容易被忽略的label标签

    # 容易被忽略的label标签 ## 原始作用 `label`标签是HTML原生的标签,其原始的作用参考[这里](http://www.w3school.com.cn/tags/tag_label.a ...

  10. 9宫拼图小游戏(WPF MVVM实现)

    昨天逛论坛,看到一个哥们用WPF做了一个9宫的拼图游戏,发现初学WPF的人都很容易犯一个错误(我也犯过):把WPF当WINFORM用!所以想写一个比较符合WPF风格的版本,于是就抽工作的空余时间做了一 ...