12/12

  1. 现有以下函数,利用装饰器为此函数加上认证功能,也就是只有用户名为'python', 密码为'123'才能调用此函数,否则不允许
    def my_log(name):
    
      print('%s欢迎登陆'%(name))
    def decorator(f):
        def w(*arg,**kw):
            global n,m
            if (n == 'python') and  (m ==123) :
                return f(*arg,**kw)
            else:
                print('登录失败!哈哈哈')
        return w
    @decorator
    def my_log(name):
        print('%s欢迎登陆'%(name))
    
    n = input('name:')
    m = int(input('password:'))
    my_log(n) 
  2. 利用装饰器为函数加上统计执行时间的功能。(提示 time模块中的time()函数可以获取当前时间)

    import time
    def use(f):
        def w(*arg,**kw):
           star_time = time.time()
           print('开始运行时间%f:'% star_time)
           f(*arg,**kw)
           end_time = time.time()
           print('结束时间:%f'% end_time)
           use_time = end_time  - star_time
           print('运行时间为:%f'% use_time)
        return w
    @use
    def my_log(name):
        print('%s欢迎登陆'%(name))
    
    n = input('name:')
    m = int(input('password:'))
    my_log(n)
    

      

  

原文地址:https://www.cnblogs.com/ZHang-/p/10110105.html