装饰器

装饰器

        本质是函数,用来装饰其他函数,为其他函数添加附加功能

    原则:装饰器对被修饰函数式完全透明的,表现如下

               1不能修改被装饰函数的源代码

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

实现知识储备:

       1.函数即“变量”

       2.高阶函数

              a:把一个函数名大部分做实参传递给另一个函数(在不修改被装饰函数源代码的情况下为期添加功能)

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

                  示例:

         import time
def test():
time.sleep(3)
print('run the test')

def test2(func):
print(func)
return(func)
test=test2(test)

test()

       3.嵌套函数

           在test函数内用def定义了find函数,find函数只能在test函数内被调用

增加时间的装饰器test示例:

import time
def test(func): #test(test1,test2)
def timer(*args,**kwargs):
start_time=time.time()
func(*args,**kwargs) #运行test1(),test2(ch1)
stop_time=time.time()
print("runing time is %s"%(stop_time-start_time))
return timer #返回timer函数的内存地址

@test #test1=test(test1)#若@test要增加条件,如@test(auth_type)
def test1( ):
time.sleep(3)
print("run the test1")
@test #test2=test(test2)

def test2(ch1):
time.sleep(3)
print("run the test2")
Print('test2:',ch1)

test1() #实际执行test
test2('power',1) #test2:power


完全版:
user,passwd='w','1'
def visit(vist_type):
def logger(func):
def web(*args,**kwargs):
if vist_type == 'local':
user_name=input("请输入用户名:").strip()
password = input("请输入密码:").strip()
if user_name == user and passwd == password:
print("欢迎%s登录"%user_name)
return func(*args,**kwargs)
# con = func(*args,**kwargs)
# print('welcome home')
# return con
else:
print("用户名或密码错误,请重新登录")
elif vist_type == 'remote':
print("正在进行远程认证")
return web
return logger

def register():
print("欢迎游客登录")

@visit(vist_type='local') #home=logger(home)
def home():
print("欢迎用户登录")
return 'welcome home'

@visit(vist_type='remote')
def forum():
print("欢迎登录论坛")

register()
print(home())
forum()







posted @ 2019-07-08 20:27  远处是风景  阅读(7)  评论(0)    收藏  举报