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

python 装饰器

时间:2014-11-23 07:00:31      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:style   blog   ar   color   sp   for   strong   on   div   

1.

>>> def deco(func):
...     print "In deco"
...     return func
...
>>> @deco
... def foo():
...     print "In foo"
...
In deco                 #因为deco()返回的 func 本身
>>>

>>>foo()
In foo

 

2.改进

>>> def deco(func):
...    print "in deco"
...    def wrapper():
...         print "wrapper start"
...         func()
...         print "wrapper end"
...    return wrapper
...
>>>
>>> @deco
... def foo():
...   print "foo"
...
in deco
>>>
>>>
>>> foo()
wrapper start
foo
wrapper end

在非交互模式下输出:

in deco
wrapper start
foo
wrapper end

 

 

3.怎么装饰不同参数的多个函数

def deco(func):
    def wrapper(*args, **kwargs):
        print "Wrap start"
        func(*args, **kwargs)
        print "Wrap end"
    return wrapper

@deco
def foo(x):
    print "In foo():"
    print "I have a para: %s" % x

@deco
def bar(x,y):
    print "In bar():"
    print "I have two para: %s and %s" % (x, y)

@deco
def foo_dict(x,z=dict_para):
    print "In foo_dict:"
    print "I have two para, %s and %s" % (x, z)

if __name__ == "__main__":
    foo(x)
    bar(x, y)
    foo_dict(x, z=dict_para)

 

4.让装饰函数名更有意义些:带参数的装饰函数

def deco(arg):
    def _deco(func):
        def wrapper():
            print("before %s called [%s]." % (func.__name__, arg))
            func()
            print("after %s called [%s]." % (func.__name__, arg))
        return wrapper
    return _deco
 
@deco("module1")             #可以填插入类型
def insert_balance():
    print("insert into balance")
 
@deco("module2")
def insert_customer():
    print("insert into customer")

 

python 装饰器

标签:style   blog   ar   color   sp   for   strong   on   div   

原文地址:http://www.cnblogs.com/yuyutianxia/p/4116082.html

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