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

    Python 装饰器,开放封闭原则

    1. 装饰器:装饰,装修,体验更加,增加功能

    2. 开放封闭原则: 开放:对代码的拓展开放

      ​ 关闭:对源码的修改关闭

    3. 装饰器:完全遵循开放封闭原则

      在不改变原函数的代码以及调用方式下,为其增加新的功能

      装饰器 就是一个函数 :

    # -*- coding: utf-8 -*-
    import time
    
    
    def login():
        time.sleep(1)
        print('123132')
    
    
    def timecheck(func):
        def inner():
            oldtime = time.time()
            func()
            newtime = time.time()
            print((newtime-oldtime))
        return inner
    
    login = timecheck(login)		#不改变源代码 不改变调用方式 新增 所消耗时间的输出
    
    login()
    

    ​ 4.python 对装饰器进行了优化,提出了语法糖的概念

    # -*- coding: utf-8 -*-
    import time
    #timecheck装饰器
    def timecheck(func):
        def inner():
            oldtime = time.time()
            func()
            newtime = time.time()
            print((newtime-oldtime))
        return inner
    
    @timecheck		#timecheck装饰器
    def login():
        time.sleep(1)
        print('123132')
    
    login()
    
    1. 装饰器 添加参数,返回值:

      # -*- coding: utf-8 -*-
      import time
      #timecheck装饰器
      def timecheck(func):
          def inner(*args,**kwargs):
              oldtime = time.time()
              revar = func(*args,**kwargs)
              newtime = time.time()
              print((newtime-oldtime))
              return revar
          return inner
      
      @timecheck
      def login(name,date):
          time.sleep(1)
          print(f'welcome {name},{date}')
          return 'loginover'
      
      
      a = login('panda',6666)
      
      print(a)
      

    标准装饰器:

    #标准装饰器:
    def wrapper(func):
        def inner(*args,**kwargs):
            #添加额外的功能
            re = func(*args,**kwargs)
            #添加额外的功能
            return re
    
    @wrapper
    def ...
    
    
  • 相关阅读:
    C#正则表达式判断输入日期格式是否正确
    Linq 总结
    sql存储过程
    uploadify多文件上传实例--C#
    Get W3WP List when Debugging
    SharePoint 2010 BI:Chart Web Part
    Versioning SharePoint 2010 Workflow In VS
    Multilingual User Interface (MUI) In SharePoint 2013
    Create Custom Modification Form In VS 2012-Part1
    Create Custom Modification Form In VS 2012-Part2
  • 原文地址:https://www.cnblogs.com/pandaa/p/12057092.html
Copyright © 2011-2022 走看看