您的位置:首页 > 编程语言 > Python开发

Python decorator 1: 函数

2016-04-13 19:51 477 查看
A.把要装饰的方法作为输入参数,

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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: