python3 装饰器

#Author by Andy
#_*_ coding:utf-8 _*_
#装饰器的原则及构成:
# 原则:
# 1、不能修改被装饰函数的源代码。
# 2、不能修改被装饰函数的调用方式。
# 3、不能改变被装饰函数的执行结果。
# 装饰器对被装饰函数是透明的。
#
# 如何理解装饰器
# 1、函数即“变量”
# 2、高阶函数
# a:把一个函数名作为实参传递给另外一个函数
# b:返回值中包含函数名
# 3、嵌套函数
#
# 在一个函数体内声明另一个函数称为函数的嵌套
#装饰器例子:
import time
# def timmer(func):
# def warpper(*args,**kwargs):
# start_time=time.time()
# func()
# stop_time=time.time()
# print('the func run time is %s'%(stop_time-start_time))
# return warpper
# @timmer
# def func1():
# time.sleep(5)
# print("I'm a test!")
# func1()
##########################################################################
#1、函数即变量
# def func2(x):
# print('i am %s'%x)
# func3()
# def func3():
# print("func3")
# return "func3"
# func2(func3())
##########################################################################
# 2、高阶函数
# a:把一个函数名作为实参传递给另外一个函数
# b:返回值中包含函数名
#定义一个高阶函数func4
# def func4(func):
# print("i am func4")
# func()
# return func
# def test():
# print("i am test")
# func4(test)
# func4(test)()
##########################################################################
#3、嵌套函数的的局部作用域与全局作用域的访问顺序
x=0
def grandpa():
x=1
def dad():
x=2
def son():
x=3
print(x)
son()
dad()
grandpa()
##########################################################################
#给已知函数test1,test2添加计算函数执行时间的功能
#定义装饰器
def timer1(func):
def deco(*args,**kwargs):
start_time=time.time()
res = func(*args,**kwargs)
stop_time=time.time()
print("The func run time is %s"%(stop_time-start_time))
return res
return deco
#定义test1、test2
@timer1
def test1():
time.sleep(3)
print("I am test1")
@timer1
def test2(x):
time.sleep(4)
print("I am test2's args %s" %x)
return "I am test2"
#test1()
#test2("hello")
print(test2("hello"))
############################################################################
#定义一个登录验证的装饰器,且根据不同情况,使用不通的验证方式:local、ldap
user,passwd='andy','123abc'
def auth(auth_type):
def out_wrapper(func):
def wrapper(*args,**kwargs):
if auth_type == 'local':
username=input("Input username:")
password=input("Input password:")
if user==username and passwd == password:
print("Welcome!")
return func(*args,**kwargs)
else:
print("Wrong username or password!")
exit()
elif auth_type == 'ldap':
print("Sorry, ldap isn't work!")
return wrapper
return out_wrapper
def index():
print("welcome to index page")
@auth(auth_type="local")
def home():
print("welcome to home page")
@auth(auth_type="ldap")
def bbs():
print("welcome to bbs page")

index()
home()
bbs()
posted @ 2016-12-09 15:07  想自由  阅读(2403)  评论(0编辑  收藏  举报