先来一个简单的例子:
#!/usr/bin/env python
def log(func): #接受被装饰函数
def dec(*argv,**kwargs): #接受被装饰函数的参数
print("this is a add exaple!!")
return func(*argv,**kwargs) #接受被装饰函数的参数
return dec
@log
def test(name,age):
print("this is a test example!! %s %s" % (name,age))
if __name__=="__main__":
test("liujiangbu",27)
z装饰器带参数:
!/usr/bin/env python
encoding: utf-8
def start_info():
print ('电视剧开头曲.......')
print ('开始唱歌.......')
def end_info():
print ('电视剧结束曲.......')
def filter(start_info,end_info): #接收俩函数
def outer(main_fun): #接收装饰的函数
def app(argv,kwargs): #接收装饰的函数的参数
print('******************************')
start_info()
main_fun(argv,**kwargs)#接收装饰的函数的参数
end_info()
print('******************************')
return app
return outer
先把函数传进去,然后在用里面的函数装饰
传函数的装饰器必须有三个def ,第一个是接受函数,第二个是装饰函数的,返回第三个函数对象
把需要装饰的函数重新定义,然后调用调用
1: filter(start_info,end_info):
2: @outer -> one_info = outer(one_info)
@filter(start_info,end_info) #这里传入俩个函数
def one_info(name,info):
print ('this is one')
print('wolcome to tv %s .......' % (name))
print('wolcome to tv %s .......' % (info))
@filter(start_info,end_info)
def two_info(name,info):
print('this is two')
print('wolcome to tv %s .......' % (name))
print('wolcome to tv %s .......' % (info))
@filter(start_info,end_info)
def three_info(name,info):
print('this is three')
print('wolcome to tv %s .......' % (name))
print('wolcome to tv %s .......' % (info))
if name == "main":
print('三国演义三部曲开始。。。。。。。。')
print('第一部。。。。。。。。。。。。。。')
one_info('三国电视剧第一部', '三国大战')
print('第二部。。。。。。。。。。。。。。')
two_info('三国电视剧第二部', '三国英雄')
print('第三部。。。。。。。。。。。。。。')
three_info('三国电视剧第三部', '三国鼎力')
装饰器不带参数:
!/usr/bin/env python
encoding: utf-8
def start_info():
print ('电视剧开头曲.......')
print ('开始唱歌.......')
def end_info():
print ('电视剧结束曲.......')
def outer(main_fun): #接收装饰的函数
def app(argv,kwargs): #接收装饰的函数的参数
print('******************************')
start_info()
main_fun(argv,**kwargs)#接收装饰的函数的参数
end_info()
print('******************************')
return app
1: @outer -> one_info = outer(one_info)
@outer
def one_info(name,info):
print ('this is one')
print('wolcome to tv %s .......' % (name))
print('wolcome to tv %s .......' % (info))
@outer
def two_info(name,info):
print('this is two')
print('wolcome to tv %s .......' % (name))
print('wolcome to tv %s .......' % (info))
@outer
def three_info(name,info):
print('this is three')
print('wolcome to tv %s .......' % (name))
print('wolcome to tv %s .......' % (info))
if name == "main":
print ('三国演义三部曲开始。。。。。。。。')
print ('第一部。。。。。。。。。。。。。。')
one_info('三国电视剧第一部','三国大战')
print('第二部。。。。。。。。。。。。。。')
two_info('三国电视剧第二部','三国英雄')
print('第三部。。。。。。。。。。。。。。')
three_info('三国电视剧第三部','三国鼎力')
http://www.cnblogs.com/cicaday/p/python-decorator.html
网友评论