zoukankan      html  css  js  c++  java
  • python基础---装饰器

    1,装饰器:

    1)为什么要用装饰器:因为你开发的程序一旦上市,就要遵守源代码开放并且尽量不能修改源代码,函数的调用方式也尽量不要修改,新的需求来了,每一       款软件都是需要更新的,在不修改源代码,不修改函数调用方式,同时还要增加新的功能,怎么实现呢?所以有了装饰器,来满足我们的条件。

    2)什么是装饰器:顾名思义,装饰就是修饰,器相当于函数

    3)装饰器定义:其本质就是一个函数,功能是为其他函数添加新的一个功能。

    2,举例:

    1) 现在来建立一个最简单的函数,这组函数值打印“welcome to oldboy” 这个语句

    1 def index():
    2     print("welcome to oldboy")
    3 index()

     2)现在我的需求来了,不能修改源代码,不能修改函数调用方式,而且还要增加一个查看这组函数运行时间的功能,怎么来实现呢? 这就要用装饰器了

     1 import time  #定义一个时间模块
     2 
     3 def timmer(tom):
     4     def wrapper():
     5         star_time = time.time()#开始时间
     6         tom()
     7         stop_time = time.time()#结束时间
     8         print("run time is %s" %(star_time-stop_time))
     9     return wrapper
    10 
    11 
    12 @timmer  #装饰器调用语法:  @调用的函数名
    13 def index():
    14     print("welcome to oldboy")
    15 index()

    3)这段程序就实现了上述要求,运行结果如下:

    welcome to oldboy
    run time is 0.0 

    4)上面也是无参装饰器的简单实现方法

    5)有无参装饰器就有有参装饰器,有参装饰器的简单实现,认证用户登录,如下

     1 def auth1(auth_type):
     2     def auth(fuhc):
     3         def wrapper(*args,**kwargs):
     4             if auth_type == "file":
     5                 name = input("please your is name >>>>>:")
     6                 passwrod = input("pleale your is passwrod >>>>>>:")
     7                 if name == "gaoyuan" and passwrod == "123":
     8                     print("hello %s wlecome to here".center(50,"-") %(name))
     9                     res = fuhc(*args, **kwargs)
    10                     return res
    11                 else:
    12                     print("bye".center(50,"-"))
    13             elif auth_type == "sql":
    14                 print("------bye-------")
    15         return wrapper
    16     return auth
    17 
    18 
    19 @auth1(auth_type = "file")  # index=auth(index)
    20 def index():
    21     print("you'll feel great ".center(50,"-"))
    22 
    23 
    24 index()

    6)输入正确,运行结果如下

    please your is name >>>>>:gaoyuan
    pleale your is passwrod >>>>>>:123
    -------------hello gaoyuan wlecome to here-------------
    ----------------you'll feel great ----------------

    7)输入错误,运行结果如下

    please your is name >>>>>:alex
    pleale your is passwrod >>>>>>:123
    -----------------------bye------------------------
  • 相关阅读:
    如何使用类
    面向过程编程与面向对象优缺点
    生成器和迭代器的藕断丝连
    三元运算
    python 和pycharm 安装
    命令提示符玩法
    模块
    包(package)
    logging模块
    1964、1969和1972---------为什么中国互联网大佬出生在这3个年份
  • 原文地址:https://www.cnblogs.com/gaoyuan111/p/6691372.html
Copyright © 2011-2022 走看看