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()
原文地址:https://www.cnblogs.com/cansun/p/8076153.html