• python 通用装饰器,带有参数的装饰器,


    # 使用装饰器对有返回值的函数进行装饰
    # def func(functionName):
      # print('---func-1----')
      # def func_in():
        # print("----func_in---1-")
        # x = functionName() #保存返回来的hahah
        # print("----func_in---2-")
        # return x
      # print('---func-2----')
      # return func_in

    # @func
    # def test():
      # print("-----test-----")
    # return "haha"

    # ret = test()
    # print("test return value is %s"%ret)

    # ---func-1----
    # ---func-2----
    # ----func_in---1-
    # -----test-----
    # ----func_in---2-
    # test return value is haha


    # 使用通用装饰器对函数进行装饰
    # def func(functionName):
      # def func_in(*args,**kwatgs):
        # print("记录日志")
        # x = functionName(*args,**kwatgs)
        # return x
      # return func_in

    # @func
    # def test():
      # print("-----test-----")
    # return "haha"

    # ret = test()
      # print("test return value is %s"%ret)
    # # -----test-----
    # # test return value is haha

    # @func
    # def test2():
      # print("----test2----")

    # a = test2()
      # print(a)
    # # ----test2----
    # # None

    # @func
    # def test3(a):
      # print("-----test3----a=%d"%a)

    # test3(10)
    # -----test3----a=10

    # 记录日志
    # -----test-----
    # test return value is haha

    # 记录日志
    # ----test2----
    # None

    # 记录日志
    # -----test3----a=10

    # 带有参数的装饰器、、
    def func_arg(arg):
      print(arg)
      def func(functionName):
        print('----func----')
        def func_in():
          print("--记录日志---")
          print(arg)
          if arg=='呵呵':
            functionName()
            functionName()
          else:
            functionName()
        return func_in
      return func

    # 1.先执行func_arg('呵呵')函数,这个函数return的结果是func这个函数的引用
    # 2.@func
    # 3.使用@func对test进行装饰

    # 带有参数的装饰器,能够起到在运行时,有不同的功能
    @func_arg('呵呵')
    def test():
      print("-----test-----")

    ret = test()
    # 呵呵
    # ----func----
    # --记录日志---
    # -----test-----

    @func_arg("haha")
      def test2():
    print("--test2--")

    test2()

    # haha
    # ----func----
    # --记录日志---
    # haha
    # --test2--

  • 相关阅读:
    《游戏改变世界》笔记
    2017第6周日
    换个角度看执行力
    怎样拥有执行力和高效能
    提高个人执行力的五个关键
    Apache服务器部署多个进程
    IE的Cookie目录和临时缓存目录的关系
    IE/Firefox/Chrome等浏览器保存Cookie的位置
    在浏览器中简单输入一个网址,解密其后发生的一切(http请求的详细过程)
    如何设置win7系统的文件夹为系统文件,从而隐藏文件夹
  • 原文地址:https://www.cnblogs.com/sklhtml/p/9447801.html
Copyright © 2020-2023  润新知