python修饰器_【python3】修饰器简单理解

修饰器

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

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

修饰器的理解

原函数没有参数

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

def makebold(fn):

def wrapped():

return "" + fn() + ""

return wrapped

def makeitalic(fn):

def wrapped():

return "" + fn() + ""

return wrapped

@makebold

@makeitalic

def hello():

return "hello world"

print hello() ## 返回 hello world

原函数有参数

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值