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

python装饰器

时间:2016-10-31 13:03:43      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:print   装饰器   ret   turn   odi   res   示例   result   call   

示例一:

# coding=utf8

def deco(func):
  # 参数不确定的函数
def _deco(*args, **kwargs): print(before %s called. % func.__name__) ret = func(*args, **kwargs) print(after %s called. result: %s % (func.__name__, ret)) return _deco @deco def myfunc(a, b): print(myfunc(%s, %s) called. % (a, b)) return a + b @deco def myfunc2(a, b, c): print(myfunc2(%s, %s, %s) called. % (a, b, c)) return a + b + c myfunc(1, 2) myfunc(3, 4) myfunc2(1, 2, 3) myfunc2(3, 4, 5)

 

让装饰器带参数

 

# coding=utf8

# 让装饰器带参数
def deco(arg):
    def _deco(func):
        def __deco():
            print(before %s called [%s]. % (func.__name__, arg))
            func()
            print(after %s called [%s]. % (func.__name__, arg))
        return __deco
    return _deco

@deco(mymodule)
def myfunc():
    print(myfunc() called.)

@deco(module2)
def myfunc2():
    print(myfunc2() called.)

myfunc()
myfunc2()

 

python装饰器

标签:print   装饰器   ret   turn   odi   res   示例   result   call   

原文地址:http://www.cnblogs.com/lqcdsns/p/6015186.html

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