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

例如:

#!/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. redis单例模式写法

    <?php /**只看红色重点 * =========================================================== * ZW_Memory_Cache * ...

  2. python中如何对待易过期的cookies

    有时候,我们进行爬虫操作是,会使用reques的的post函数携带cookies访问目标网站已达到登录或者其他 目的,笔者最近就遇到了这样的案例,周六写好的代码,周一过来就不行了,重新登录访问目标网页 ...

  3. mac sourcetree push分支选中所有tag的时候报错

    错误信息: ....... ! [rejected] 573_0811_stable -> 573_0811_stable (already exists)updating local trac ...

  4. Hadoop Yarn调度器的选择和使用

    一.引言 Yarn在Hadoop的生态系统中担任了资源管理和任务调度的角色.在讨论其构造器之前先简单了解一下Yarn的架构. 上图是Yarn的基本架构,其中ResourceManager是整个架构的核 ...

  5. 如何编写.NET Core Global Tools (附两个案例)

    一.什么是 .NET Core Global Tools 2018年5月31日(北京时间)微软发布了 .NET Core 2.1 正式版,.NET Core 2.1 为我们带来了一个新的特性:.NET ...

  6. 图解Redis之数据结构篇——字典

    前言     字典在Redis中的应用非常广泛,数据库与哈希对象的底层实现就是字典. 系列文章 图解Redis之数据结构篇--简单动态字符串SDS 图解Redis之数据结构篇--链表 图解Redis之 ...

  7. [蛙蛙推荐]SICP第一章学习笔记-编程入门

    本书简介 <计算机程序的构造与解释>这本书是MIT计算机科学学科的入门课程, 大部分学生在学这门课程前都没有接触过程序设计,也就是说这本书是针对编程新手写的. 虽然是入门课程,但起点比较高 ...

  8. Krpano教程tour.xml详解

    <krpano version="1.18" //版本号 onstart="" //网页启动时调用的函数 basedir="%FIRSTXML% ...

  9. STL queue用法

    先进先出 #include<iostream> #include<algorithm> #include<cstdio> #include<stack> ...

  10. 后台管理系统之邮件开发(Java实现)

    一,功能点 后台管理系统,添加用户时.对注册的新用户邮箱发送初始密码. 二,代码实现 1.Mail实体类 public class Mail { private Set<String> r ...