• python 装饰器 (多个参数的函数,带参数的装饰器)


    最简单的模板是这样的

     1 #-*-coding:utf-8-*-
     2 
     3 def outer(func):
     4     def inner():
     5         print 'before'
     6         func()
     7         print 'after'
     8         # return r
     9     return inner
    10 '''
    11 def outer_1(func):
    12     def inner():
    13         print 'before 11'
    14         func()
    15         print 'after 22'
    16         # return r
    17     return inner
    18 
    19 @outer_1
    20 '''
    21 @outer
    22 def F1():
    23     print 'test'
    24 
    25 if __name__ == '__main__':
    26     F1()
    27 '''
    28 运行结果
    29 before
    30 test
    31 after
    32 [Finished in 0.1s]
    33 '''
    View Code

    --装饰器也能用2个,把注释打开

    函数带多个参数,装饰器对应修改以适合多种情况

     1 # -*- coding: utf-8 -*-
     2 
     3 from time import ctime
     4 from time import sleep
     5 
     6 def ftfunc(func):
     7     def timef(*s,**gs):
     8         print "[%s] %s() called" % (ctime(),func.__name__)
     9         return func(*s,**gs)
    10     return timef
    11 
    12 @ftfunc
    13 def foo(*s,**gs):
    14     print(s)
    15     print(gs)
    16 
    17 if __name__ == '__main__':
    18     foo()
    19     foo(1)
    20     foo(1,2)
    21     foo(1,2,3)
    22     stu = {'name' : 'alam' ,'age' :12}
    23     foo(1,2,3,**stu)
    24 '''
    25 运行结果
    26 [Wed Jun 14 15:49:55 2017] foo() called
    27 ()
    28 {}
    29 [Wed Jun 14 15:49:55 2017] foo() called
    30 (1,)
    31 {}
    32 [Wed Jun 14 15:49:55 2017] foo() called
    33 (1, 2)
    34 {}
    35 [Wed Jun 14 15:49:55 2017] foo() called
    36 (1, 2, 3)
    37 {}
    38 [Wed Jun 14 15:49:55 2017] foo() called
    39 (1, 2, 3)
    40 {'age': 12, 'name': 'alam'}
    41 [Finished in 0.1s]
    42 
    43 '''
    View Code

    函数带多个参数,装饰器也带多个参数

     1 # -*- coding: utf-8 -*-
     2 
     3 def decrator(*dargs, **dkargs):
     4     def wrapper(func):
     5         def _wrapper(*args, **kargs):
     6             print "decrator param:", dargs, dkargs
     7             print "function param:", args, kargs
     8             return func(*args, **kargs)
     9         return _wrapper
    10     return wrapper
    11 
    12 @decrator(1, a=2)
    13 def foo(x, y=0):
    14     print "foo", x, y
    15 
    16 
    17 if __name__ == '__main__':
    18     foo(3, 4)
    19 
    20 '''
    21 执行结果
    22 decrator param: (1,) {'a': 2}
    23 function param: (3, 4) {}
    24 foo 3 4
    25 [Finished in 0.1s]
    26 '''
    View Code

     函数带多个参数,装饰器能转换参数类型

     1 # -*- coding: utf-8 -*-
     2 
     3 def validate(**vkargs):
     4     def decorator(func):
     5         def wrapper(**kargs):
     6             for key in vkargs:
     7                 # 根据vkargs中的参数的类型对kargs的参数进行类型转换
     8                 kargs[key] = vkargs[key](kargs[key])
     9             return func(**kargs)
    10         return wrapper
    11     return decorator
    12 
    13 
    14 @validate(x=int, y=float, z=float)
    15 def move(x, y, z):
    16     print "move %d (%0.2f, %0.2f)"%(x, y, z)
    17 
    18 
    19 
    20 if __name__ == '__main__':
    21     move(x="1", y="0.2", z="0.3")
    22 '''
    23 运行结果
    24 move 1 (0.20, 0.30)
    25 [Finished in 0.2s]
    26 '''
    View Code

     一个简单的例子,登录页面

     1 # -*- coding: utf-8 -*-
     2 
     3 #模拟网站登陆访问认证
     4 
     5 name = 'abc'
     6 password='123'
     7 
     8 def certi(model):#装饰器
     9     def outr(fun):#装饰器加参数需要多加一层嵌套
    10         def login(*args,**kwargs):#为了兼容各类函数参数,添加 *args,**kwargs 不固定参数
    11             if model=='password':
    12                 print('enter password')
    13                 user_name = raw_input('user_name ').strip()
    14                 paswd=raw_input('password ').strip()
    15                 if user_name==name and paswd==password:
    16                     print('pass')
    17                     return fun(*args,**kwargs)
    18                 else:
    19                     print('error ')
    20                     exit()
    21             elif model=='lamp':
    22                 print('this is lamp')
    23                 return fun(*args,**kwargs)
    24             else:
    25                 print('error')
    26         return login
    27     return outr
    28 
    29 
    30 def indxe():
    31     print('home page !!')
    32 
    33 @certi(model='password')
    34 def user():
    35     print('user page !!')
    36 
    37 @certi(model='lamp')
    38 def bbs(name):
    39     print('bbs %s!!'%name)
    40 
    41 
    42 
    43 if __name__ == '__main__':
    44     indxe()
    45     user()
    46     bbs(name='yjj')
    47 '''
    48 运行结果
    49 home page !!
    50 enter password
    51 user_name abc
    52 password 123
    53 pass
    54 user page !!
    55 this is lamp
    56 bbs yjj!!
    57 '''
    View Code

     -----------------20170711 再次理解-----------------

    1.简单的装饰器

    2.带参数的装饰器

     3.多个装饰器

  • 相关阅读:
    Liunx基础优化配置
    Linux配置国内的Yum源
    Liunx配置静态IP
    百度前端学院|任务七
    java的远程访问接口的实例
    java套接字实现接口访问
    Mysql的链接超时异常CommunicationsException
    mysql查看和设置timeout 和批量杀死链接进程
    springmvc接受表单多条数据的值
    jquery获取点击标签内的子标签内容和值实例
  • 原文地址:https://www.cnblogs.com/alamZ/p/7007945.html
Copyright © 2020-2023  润新知