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

    1、装饰器:
    定义:本质是函数,用于装饰其他函数:就是为其他函数添加附加功能。
    原则:1.不能修改被装饰的函数的源代码
    2.不能修改被装饰的函数的调用方式
    2、实现装饰器知识储备:
    1). 函数即“变量” #大楼房间-门牌号 -->内存释放机制
    2). 高阶函数
    a: 把一个函数名当作实参传给另一个函数(在不修改被装饰函数源代码的情况下为其添加功能)
    b: 返回值中包含函数名(不修改函数的调用方式)
    3). 嵌套函数
    3、高阶函数 + 嵌套函数 =》 装饰器

    示例一(初级):装饰器作用,计算被装饰函数的执行时间。
     1 # -*- coding:utf-8 -*-
     2 import time
     3 
     4 def timer(func):
     5     def deco(*args,**kwargs):
     6         start_time = time.time()
     7         func(*args,**kwargs)
     8         stop_time = time.time()
     9         print("the func run time is %s" %(stop_time-start_time))
    10     return deco
    11 
    12 @timer
    13 def test1():
    14     time.sleep(2)
    15     print("in the test1")
    16 
    17 @timer      # @timer等价于:test2=timer(test2)=deco
    18 def test2(name,age):
    19     time.sleep(3)
    20     print("info:%s,%s" %(name, age))
    21 
    22 test1()
    23 test2("tj", 23)  #等价于:deco("tj", 23)
    24 
    25 >>>
    26 in the test1
    27 the func run time is 2.009901523590088
    28 info:tj,23
    29 the func run time is 3.009861946105957

    示例二(进阶)、装饰器作用,进入页面前进行用户验证,当进入home页面时,使用验证方法a,当进入bbs页面时,使用验证方式b,此示例中没有b验证方式,仅演示a验证方式。

     1 user="abc"
     2 password="abc123"
     3 
     4 def auto_outside(type):
     5     def wrpper(func):
     6         def deco(*args, **kwargs):
     7             if type == "a":
     8                 username=input("Username:")
     9                 passwd=input("Password:")
    10                 if username==user and passwd==password:
    11                     print("登录成功")
    12                     return func(*args, **kwargs)
    13                 else:
    14                     print("用户名或密码错误")
    15             elif type == "b":
    16                 print("用什么b")
    17         return deco
    18     return wrpper
    19 
    20 def index():
    21     print("welcome to index pages")
    22 
    23 @auto_outside(type="a")  #type为验证方式类型
    24 def home():
    25     print("welcome to home pages")
    26     return "from home"
    27 
    28 @auto_outside(type="b")
    29 def bbs():
    30     print("welcome to bbs pages")
    31 
    32 index()
    33 print(home())
    34 bbs()
    35 
    36 >>>
    37 welcome to index pages  # index页面不需要验证
    38 Username:abc
    39 Password:abc123
    40 登录成功
    41 welcome to home pages   # home页面使用a验证方式,登录成功后进入页面
    42 from home 
    43 用什么b  # 进入bbs页面前提示没有b验证方式
     
  • 相关阅读:
    Log4net<转载>
    XSD使用《转载》
    assemble文件中配置
    常用工具《收藏》
    mysql查看所有存储过程,函数,视图,触发器,表《转》
    log4g net 配置
    XSLT使用<转载>
    C#操作xml之xpath语法<收藏>
    如何做镜像服务器
    Android开发之旅:环境搭建及HelloWorld
  • 原文地址:https://www.cnblogs.com/sunnytomorrow/p/13081073.html
Copyright © 2011-2022 走看看