python中修饰器是什么?

Python016

python中修饰器是什么?,第1张

就是一个callable object。 它使python编程更加容易。

例如:

@dec

def A(args):

pass

它就等价于dec(A). 当然还有带参数的decorator。我就不举例了。

python文档里有这样一句话。

A function definition may be wrapped by one or more decorator expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators are applied in nested fashion.

大概就是说函数的定义可以用多个decorator。decorator就在函数定义时用函数作为参数调用,然后返回一个可调用对象。 所以写decorator的时候一定要返回一个可调用对象。

不知道你明白没。

#Python 2.5 #这个可以用修饰器来完成 #但是一般不会限制参数类型 #给你个思路: def argfilter(*types): def deco(func): #这是修饰器 def newfunc(*args): #新的函数 if len(types)==len(args): correct = True for i in range(len(args)): if not isinstance(args[i], types[i]): #判断类型 correct = False if correct: return func(*args) #返回原函数值 else: raise TypeError else: raise TypeError return newfunc #由修饰器返回新的函数 return deco #返回作为修饰器的函数 @argfilter(int, str) #指定参数类型 def func(i, s): #定义被修饰的函数 print i, s #之后你想限制类型的话, 就这样: #@argfilter(第一个参数的类名, 第二个参数的类名, ..., 第N个参数的类名) #def yourfunc(第一个参数, 第一个参数, ..., 第N个参数): # ... # #相当于: #def yourfunc(第一个参数, 第一个参数, ..., 第N个参数): # ... #yourfunc = argfilter(第一个参数的类名, 第二个参数的类名, ..., 第N个参数的类名)(yourfunc)