标签:就是 类型转换 class code alt inf wrapper fun function
函数修饰符
‘@‘ 用做函数的修饰符,可以在模块或者类的定义层内对函数进行修饰,
出现在函数定义的前一行,不允许和函数定义在同一行
一个修饰符就是一个函数,它将被修饰的函数作为参数,并返回修饰后的同名函数或其他可调用的东西?
示例:
def test(fn): def d(*args): print("1-----",args) n=args[0] print("2----",n) print(fn.__name__) fn(n*n) print("*"*15) return fn(3) return d @test def sum_a(a): print("3==",a) 调用: In[15]: sum_a(10) #结果 1----- (10,) 2---- 10 sum_a 3== 100 *************** 3== 3
1.最简单的装饰器:
2.带参数的装饰器
3.多个装饰器:
4.函数带多个参数,装饰器也带多个参数
# -*- coding: utf-8 -*- def decrator(*dargs, **dkargs): def wrapper(func): def _wrapper(*args, **kargs): print "decrator param:", dargs, dkargs print "function param:", args, kargs return func(*args, **kargs) return _wrapper return wrapper @decrator(1, a=2) def foo(x, y=0): print "foo", x, y if __name__ == ‘__main__‘: foo(3, 4) ‘‘‘ 执行结果 decrator param: (1,) {‘a‘: 2} function param: (3, 4) {} foo 3 4 [Finished in 0.1s] ‘‘‘
5.函数带多个参数,装饰器能转换参数类型
# -*- coding: utf-8 -*- def validate(**vkargs): def decorator(func): def wrapper(**kargs): for key in vkargs: # 根据vkargs中的参数的类型对kargs的参数进行类型转换 kargs[key] = vkargs[key](kargs[key]) return func(**kargs) return wrapper return decorator @validate(x=int, y=float, z=float) def move(x, y, z): print "move %d (%0.2f, %0.2f)"%(x, y, z) if __name__ == ‘__main__‘: move(x="1", y="0.2", z="0.3") ‘‘‘ 运行结果 move 1 (0.20, 0.30) [Finished in 0.2s] ‘‘‘
标签:就是 类型转换 class code alt inf wrapper fun function
原文地址:https://www.cnblogs.com/lyy-blog/p/9797830.html