码迷,mamicode.com
首页 > 编程语言 > 详细

【python3】修饰器简单理解

时间:2019-03-14 18:18:47      阅读:411      评论:0      收藏:0      [点我收藏+]

标签:函数参数   after   python   方法   wrap   return   func   app   返回值   

修饰器

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

比如说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

@w2
def 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

@w3
def 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()


@Test
def test():
    print('this is test func')


test()

#输出:
# test init
# func name is test 
# this is wrapper
# this is test func

【python3】修饰器简单理解

标签:函数参数   after   python   方法   wrap   return   func   app   返回值   

原文地址:https://www.cnblogs.com/wangjian1226/p/10531702.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!