#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()