python 装饰器实现
简单装饰器实现:
# -*- coding: utf-8 -*- ''' 装饰器的特点:对原函数是透明的 实现方式是: 高阶函数+ 嵌套函数 ''' from _ctypes_test import func def decorator(func): ''' 定义装饰器 *args,**kwargs 这两个是为了接收不固定的参数 ''' def test(*args,**kwargs): print("test 装饰器运行------>") func(*args,**kwargs) print("test 装饰器运行结束") return test ''' 使用 @decorator 这种方式(@装饰器名字)来调用装饰器 ''' @decorator def func_1(): print("func_1方法被调用") @decorator def func_2(name): print("this is func_2:",name) func_1() func_2("name")
被装饰的函数带有返回值:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
''' 被装饰的函数带返回值 ''' def decorator_re(func): def wrapper(*args,**kwargs): print("decorator is run ---->") res = func(*args,**kwargs) #接收被装饰函数的返回值 print("decorator stop ------") return res #返回 return wrapper @decorator_re def func_re(name): print("my name is :",name) return name my_name = func_re("arturo") print(my_name)
根据type 选择指定装饰器:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
''' 根据 type 运行指定的装饰器 ''' def decorator_name(decorator_type): def switch(func): def wrapper(*args,**kwargs): if decorator_type=="name": print("name decorator is run ---->") res = func(*args,**kwargs) #接收被装饰函数的返回值 print("name decorator stop ------") return res #返回 elif decorator_type=="fullName": print("fullName decorator is run ---->") res = func(*args,**kwargs) #接收被装饰函数的返回值 print("fullName decorator stop ------") return res #返回 return wrapper return switch @decorator_name(decorator_type="name") def func_name(name): print("my name is :",name) return name @decorator_name(decorator_type="fullName") def func_fullName(name): print("fullName is :",name) return name func_name("xiaoQang") func_fullName("wangwang")
posted on 2017-09-21 14:03 gaizhongfeng 阅读(141) 评论(0) 编辑 收藏 举报