zoukankan      html  css  js  c++  java
  • 装饰器

    1 基本装饰器

      基本装饰器的作用:

        在不改变原函数的基础上, 通过装饰器, 给原函数新增某些功能

      实现方法:

        在原函数上加

          @装饰器名字

          其中@叫做语法糖

        定义装饰器

          第一层函数传入参数(用于传入原函数)

          第二层使用原函数的同时, 加入需要新增的功能

          第一层函数要返回第二层函数名

          整个函数形成闭包

      定义模板

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    '基本装饰器'
    
    __author__ = 'weihuchao'
    
    
    import time
    
    def runtime(func):
        def wrapper():
            start = time.time()
            for i in range(100):
                func()
            end = time.time()
            print("程序运行时间为 {} ".format((end - start)/1000.0))
        return wrapper
    
    @runtime
    def hello():
        print("hello world")
    
    hello()
    

    2 三层装饰器

      现在需要在装饰器的基础上, 调用 @装饰器 的时候传入参数

      就需要在原有的装饰器的基础上, 在外层写一个函数, 从而又形成闭包的结构

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    '三层装饰器'
    
    __author__ = 'weihuchao'
    
    import time
    
    def runtime(msg="默认值"):
        def decorator(func):
            def wrapper():
                start = time.time()
                for i in range(100):
                    func()
                end = time.time()
                print(msg)
                print("程序运行时间为 {} ".format((end - start) / 1000.0))
            return wrapper
        return decorator
    
    @runtime("hello()")
    def hello():
        print("hello world")
    
    hello()
    

    3 完善参数传递

      在之前的装饰器中, 由于原函数可能存在不同种类的参数, 可能有各种各样的返回值, 所以要进行一下两点修改

        1 将装饰器实际执行函数的参数设置为(*, **)的形式

        2 改函数需要return 原函数

      具体实现

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    '扩展性更好的装饰器'
    
    __author__ = 'weihuchao'
    
    import time
    
    def log(msg="默认值"):
        def decorator(func):
            def wrapper(*args, **kwargs):
                print(func.__name__, msg)
                return func(*args, **kwargs)
            return wrapper
        return decorator
    
    @log("hello()")
    def hello():
        print("hello world")
    
    hello()
    

      

    人若有恒 无所不成
  • 相关阅读:
    清除富文本样式
    jquery--cookie应用
    Log4j 配置详解
    判断请求是否为ajax
    日期工具类
    Windows Server2012 KB2919355 补丁无法安装
    安装系统步骤:
    大白菜u盘启动盘制作工具取消赞助商方法详解
    视频使用教程
    检查网络是否正常的几种命令
  • 原文地址:https://www.cnblogs.com/weihuchao/p/6690350.html
Copyright © 2011-2022 走看看