Python decorator 1: 函数
2016-04-13 19:51
477 查看
A.把要装饰的方法作为输入参数,
B.在函数体内可以进行任意的操作(可以想象其中蕴含的威力强大,会有很多应用场景),
C.只要确保最后返回一个可执行的函数即可(可以是原来的输入参数函数, 或者是一个新函数)
如果只需要在被包装函数执行前插入代码,decorator可以加上插入代码后返回原函数 (例1,3)
如果需要在包装函数执行之前和之后都插入代码,decorator需要另加一个函数并返回这个函数,在这个函数中调用传入的函数(例2,4)
1. 无参数装饰器 – 包装无参数函数
等价于
2. 无参数装饰器 – 包装带参数函数
等价于
3. 带参数装饰器 – 包装无参数函数
等价于
4. 带参数装饰器– 包装带参数函数
等价于
B.在函数体内可以进行任意的操作(可以想象其中蕴含的威力强大,会有很多应用场景),
C.只要确保最后返回一个可执行的函数即可(可以是原来的输入参数函数, 或者是一个新函数)
如果只需要在被包装函数执行前插入代码,decorator可以加上插入代码后返回原函数 (例1,3)
如果需要在包装函数执行之前和之后都插入代码,decorator需要另加一个函数并返回这个函数,在这个函数中调用传入的函数(例2,4)
1. 无参数装饰器 – 包装无参数函数
def decorator(func): print "hello" return func @decorator def foo(): pass foo()
等价于
foo = decorator(foo) foo()
2. 无参数装饰器 – 包装带参数函数
def decorator_func_args(func): def handle_args(*args, **kwargs): #处理传入函数的参数 print "begin" func(*args, **kwargs) #函数调用 print "end" return handle_args @decorator_func_args def foo2(a, b=2): print a, b foo2(1)
等价于
foo2 = decorator_func_args(foo2) foo2(1)
3. 带参数装饰器 – 包装无参数函数
def decorator_with_params(arg_of_decorator):#这里是装饰器的参数 print arg_of_decorator #最终被返回的函数 def newDecorator(func): print func return func return newDecorator @decorator_with_params("deco_args") def foo3(): pass foo3()
等价于
foo3= decorator_with_params(arg_of_decorator)(foo3)
4. 带参数装饰器– 包装带参数函数
def decorator_whith_params_and_func_args(arg_of_decorator): def handle_func(func): def handle_args(*args, **kwargs): print "begin" func(*args, **kwargs) print "end" print arg_of_decorator, func, args,kwargs return handle_args return handle_func @decorator_whith_params_and_func_args("123") def foo4(a, b=2): print "Content" foo4(1, b=3)
等价于
foo4 = decorator_whith_params_and_func_args("123")(foo4) foo4(1,b=3)
相关文章推荐
- python的基本输入输出
- Python 2.7 解决写入文件的中文乱码问题
- python安装
- 如何在Python中使用静态变量在计数
- 使用Selenium+firefox抓取网页指定firefox_profile后的问题
- Python虚拟环境安装virtualenv
- python3 字符串与列表常用功能
- python 转 exe -- py2exe库实录
- python笔记 - 高级属性(20160413)
- python 列表、字典的方法
- 用python导入mysql
- 解决Python UnicodeDecodeError: ‘ascii’ codec can’t decode
- Python3.5入门学习记录-函数
- Python -- 字符串大小写转换
- python 基础学习(字典对象,set对象)
- 初学python(对比java语言不同) 第九篇
- python 基础学习(元组,if,for)
- hive+python数据分析入门
- [Python] Python基础字符串
- Python 3.5.1安装lxml