代码改变世界

4-2装饰器2

2017-11-27 23:43  mmwss  阅读(151)  评论(0编辑  收藏  举报
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#完整装饰器++++++++++ 通用的
print('###完整装饰器###')
import time

def xx(z): #装饰器
def xxx(*c,**cc):
mm=time.time()
z(*c,**cc)
ww=time.time()
print('这是装饰器+的功能:运行时间%s' %(ww-mm))
return xxx
@xx # aa=xx(aa) #不改变调用方式 在装饰器头部加
def aa():
time.sleep(1)
print('这是AA')
@xx
def bb(name):
time.sleep(1)
print('这是BB',name)

aa() #aa函数 头部加 装饰器 @xx
bb(1) #bb函数 头部没加 装饰器 @xx


print('+++简单网站登录装饰器+++')
#高级版装饰器
#有100个页面,20个页面进入要用户
user,passwd = 'aa','bb'
def aaa(x):
def bbb(*args, **kwargs):
print("第三层的值:", *args, **kwargs)
username = input("名:").strip()
password = input("码:").strip()
if user == username and passwd == password:
return x(*args, **kwargs)
else:
exit("\033[31;用户名密码不对\033[0m")

return bbb

def index():
print("这是网站首页")
@aaa
def home():
print("这是家目录")
return 'xx'

index()
home()

print('++++++网站登录装饰器++++++')
#高级版装饰器
#有100个页面,20个页面进入要用户
user,passwd = 'aa','bb'
def aaa(type):
print("第一层的值:",type)
def bbb(x):
def ccc(*args, **kwargs):
print("第三层的值:", *args, **kwargs)
if type == "local":
username = input("Username:").strip()
password = input("Password:").strip()
if user == username and passwd == password:
print("\033[32;1mUser has passed authentication\033[0m")
res = x(*args, **kwargs) # from home
print("这里可加别的装饰器")
return res
else:
exit("\033[31;1mInvalid username or password\033[0m")
elif type == "ldap":
print("搞毛线ldap,不会。。。。")

return ccc
return bbb

def index():
print("这是网站首页")
@aaa(type="local") # home = ccc()
def home():
print("这是家目录")
return "from home"

@aaa(type="ldap")
def bbs():
print("这是论坛")

index()
print(home()) #ccc()
bbs()