【python3】修饰器简单理解,,修饰器修饰器干嘛的,


修饰器

修饰器干嘛的,有什么作用

比如说A现在已经写好了一个项目,但是现在B接管了这个项目,B需要对项目中的某个函数进行修改,一个一个修改然后复制,粘贴?这时候修饰器就开始大显身手了。修饰器可以避免许多重复的动作。用@+修饰函数放在待修饰的函数头上就可以实现优化函数的功能

修饰器的理解

原函数没有参数

修饰器可以看作是一个接收函数的函数,内部再定义局部函数用来修饰传进来的函数参数

def makebold(fn):      def wrapped():          return "<b>" + fn() + "</b>"      return wrapped     def makeitalic(fn):      def wrapped():          return "<i>" + fn() + "</i>"      return wrapped    @makebold  @makeitalic  def hello():      return "hello world"     print hello() ## 返回 <b><i>hello world</i></b>

原函数有参数

修饰函数还是传函数参数,修饰函数里面的局部函数传入原函数的参数

def w2(fun):    def wrapper(*args,**kwargs):        print("this is the wrapper head")        fun(*args,**kwargs)        print("this is the wrapper end")    return wrapper@w2def hello(name,name2):    print("hello"+name+name2)hello("world","!!!")#输出:# this is the wrapper head# helloworld!!!# this is the wrapper end

需要有返回值

def w3(fun):    def wrapper():        print("this is the wrapper head")        temp=fun()        print("this is the wrapper end")        return temp   #要把值传回去呀!!    return wrapper@w3def hello():    print("hello")    return "test"result=hello()print("After the wrapper,I accept %s" %result)#输出:#this is the wrapper head#hello#this is the wrapper end#After the wrapper,I accept test

类修饰器

大体上和函数修饰器差不多,只是类不能直接调用要加上__call__方法。

class Test(object):    def __init__(self, func):        print('test init')        print('func name is %s ' % func.__name__)        self.__func = func    def __call__(self, *args, **kwargs):        print('this is wrapper')        self.__func()@Testdef test():    print('this is test func')test()#输出:# test init# func name is test # this is wrapper# this is test func

【python3】修饰器简单理解

评论关闭