首页 > 代码库 > python3--装饰器高级学习版

python3--装饰器高级学习版


__author__ = "Aaron Fan"
import time #导入time模块
user,passwd = ‘alex‘,‘abc123‘   #用户名密码
def auth(auth_type):    #创建auth函数,创建auth_type形参
   #print("auth func:",auth_type)   #打印形参auth_type的值
   def outer_wrapper(func):    #创建outer_wrapper函数,创建func形参
       def wrapper(*args, **kwargs):   #创建wrapper函数,创建非固定参数*args,**kwargs
           #print("wrapper func args:", *args, **kwargs)   #打印传进来的这些非固定参数的值
           if auth_type == "local":    #如果auth函数中的形参auth_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 = func(*args, **kwargs)  # from home    #这里主要是为了显示home()函数中的return值:from home
                   print("---after authenticaion ")    #打印一句话
                   return res  #返回定义的res变量的值


               else:   #否则账号或者密码错误
                   exit("\033[31;1mInvalid username or password\033[0m")
           elif auth_type == "ldap":   #如果auth函数中的形参auth_type的值等于ldap
               print("搞毛线ldap,不会。。。。") #ldap的处理语句,这里暂时先用一句print代替了,记得后面练习是需要去细化一下

       return wrapper  #return wrapper
   return outer_wrapper    #return outer_wrapper

# index主页,不需要用户名密码,可以直接登录,所以这里也无需装饰器
def index():
   print("welcome to index page")

#home页面,需要通过local方式来匹配用户登陆
@auth(auth_type="local") # home = wrapper()
                       #注意@auth代表auth(),@auth(auth_type="local")代表outer_wrapper()
                       #所以这里其实是指 home = outer_wrapper(home) = wrapper
def home():
   print("welcome to home  page")
   return "from home"

#bbs页面,需要通过ldap方式来匹配用户登陆
@auth(auth_type="ldap")
def bbs():
   print("welcome to bbs  page")

index()
print(home()) #其实执行的是wrapper()  这个方式会显示homereturn
#home()  #其实执行的是wrapper()   这个不会显示return
bbs()   #其实执行的是wrapper()


本文出自 “近朱者赤” 博客,请务必保留此出处http://fanheng.blog.51cto.com/974941/1881593

python3--装饰器高级学习版