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

例如:

#!/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. JDK动态代理Demo代码,进一步学习分析

    import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflec ...

  2. Idea自带工具解决冲突

    1:产生冲突 2:解决冲突 解决冲突具体操作: 手动合并代码: 此时点击的是local的>:点击changes的X则合并效果为: 也可以两侧都点击>.结果为: 也可以都点击X,结果为: 最 ...

  3. 发现一款比echarts更牛B,效果更炫的图表组件 d3.js

    每天学习一点点 编程PDF电子书.视频教程免费下载:http://www.shitanlife.com/code d3.js  ,能制作更加复杂的图表 https://github.com/d3/d3 ...

  4. php 依赖注入的实现

    当A类需要依赖于B类,也就是说需要在A类中实例化B类的对象来使用时候,如果B类中的功能发生改变,也会导致A类中使用B类的地方也要跟着修改,导致A类与B类高耦合.这个时候解决方式是,A类应该去依赖B类的 ...

  5. python3 练习题(用函数完成登录注册以及购物车的功能)

    ''' 用函数完成登录注册以及购物车的功能 作业需求: 1,启动程序,用户可选择四个选项:登录,注册,购物,退出. 2,用户注册,用户名不能重复,注册成功之后,用户名密码记录到文件中. 3,用户登录, ...

  6. markdown的使用语法的补充

    markdown的使用语法的补充 markdown的语法在网络上有很多,例如简书的教程这个是参考简书上的教程 但是有几个语法需要记住. 添加图片,如果要添加图片,他的语法格式是首先一个感叹号!然后[] ...

  7. ASP MD5

    <% Private Const BITS_TO_A_BYTE = 8 Private Const BYTES_TO_A_WORD = 4 Private Const BITS_TO_A_WOR ...

  8. Java技术——Java中的static关键字解析

    )非静态内部类能够访问外部类的静态和非静态成员,显然一个非静态内部类不能脱离外部类实体被创建,而静态类不能访问外部类的非静态成员,它只能访问外部类的静态成员.这一点和上面static方法的性质类似. ...

  9. Netty入门(二)之PC聊天室

    参看Netty入门(一):Netty入门(一)之webSocket聊天室 Netty4.X下载地址:http://netty.io/downloads.html 一:服务端 1.SimpleChatS ...

  10. 图解SSH原理及两种登录方法

    SSH(Secure Shell)是一套协议标准,可以用来实现两台机器之间的安全登录以及安全的数据传送,其保证数据安全的原理是非对称加密. 传统的对称加密使用的是一套秘钥,数据的加密以及解密用的都是这 ...