zoukankan      html  css  js  c++  java
  • python之装饰器篇

    一.基本装饰器

    基本装饰器的作用:

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

      实现方法:

        在原函数上加

          @装饰器名字

          其中@叫做语法糖

        定义装饰器

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

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

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

          整个函数形成闭包

    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()
     
    二.三层装饰器

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

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

    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()

    三.完善参数传递

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

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

        2 改函数需要return 原函数

    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()
  • 相关阅读:
    linux下使用OpenCV的一些问题
    Google Colab调用cv2.imshow奔溃
    [LeetCode] Word Search
    信号
    信号
    [Leetcode] Subsets
    [LeetCode] Combinations
    [LeetCode] Minimum Window Substring
    [LeetCode] Set Matrix Zeroes
    sigaction 函数
  • 原文地址:https://www.cnblogs.com/asaka/p/6700265.html
Copyright © 2011-2022 走看看