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

    装饰器:

    定义:本质是函数(用来装饰其他函数,即为其他函数添加附加功能)

    原则:1.不能修改被装饰的函数的源代码

        2.不能修改被装饰的函数的调用方式

    实现装饰器知识储备:

    1.函数即“变量”

    2.高阶函数

      a.把一个函数名当作实参传递给另一个函数(在不修改函数源代码的情况下为其添加功能)

      b.返回值中包含函数名(不修改函数的调用方式)

    3.嵌套函数

    高阶函数+嵌套函数=》装饰器

    #!usr/bin/env python
    # -*- coding:utf-8 -*-
    import time
    __author__ = "Samson"

    def timer(func):#高阶函数+嵌套函数=>>嵌套函数
    def deco(*args,**kwargs):#func函数可能会有若干参数(位置参数或关键字参数)
    start_time = time.time()
    func(*args,**kwargs)
    stop_time = time.time()
    print("the func runtime is %s" % (stop_time - start_time))
    return deco

    @timer#需要在哪个函数前加上装饰器,便需添加@装饰器名字(相当于test1 = timer(test1))
    def test1():
    time.sleep(3)
    print("in the test1")
    @timer#相当于test2 = timer(test2)
    def test2(name):
    time.sleep(3)
    print(name)

    test1()
    test2("sun")

    #!usr/bin/env python
    # -*- coding:utf-8 -*-

    __author__ = "Samson"
    user, passwd = "alex", "abc123"
    def auth(auth_type):
    print("auth func:", auth_type)
    def outer_wrapper(func):
    def wrapper(*args, **kwargs):
    if auth_type == "local":
    username = input("Username:").strip()
    password = input("Password:").strip()
    if user == username and passwd == password:
    print("33[32;1mUser has passed authentication33[0m")
    return func(*args, **kwargs)
    else:
    exit("33[32;1mInvalid username or password33[0m")
    return wrapper
    elif auth_type == "ldap":
    print("搞毛线ldap,不会")
    return wrapper
    return outer_wrapper
    def index():
    print("Welcome to index page")

    @auth(auth_type = "local")#通过本地验证用户名与密码
    def home():
    print("Welcome to home page")
    return "from home"
    @auth(auth_type = "ldap")#通过ldap验证用户名与密码
    def bbs():
    print("Welcome to bbs page")
    index()
    print(home())
    bbs()
  • 相关阅读:
    SQL常见问题及解决备忘
    工厂方法模式-Factory Method
    访问者模式-Visitor
    解释器模式-Interpreter
    享元模式-Flyweight
    系统的重要文件/etc/inittab被删除了--急救办法!
    Database基础(二):MySQL索引创建与删除、 MySQL存储引擎的配置
    轻松解决U盘拷贝文件时提示文件过大问题
    Cisco基础(六):配置目前网络环境、项目阶段练习
    Cisco基础(五):配置静态NAT、配置端口映射、配置动态NAT、PAT配置、办公区Internet的访问
  • 原文地址:https://www.cnblogs.com/cansun/p/8076153.html
Copyright © 2011-2022 走看看