python decorator

来源:互联网 发布:淘宝卖家插件哪个好 编辑:程序博客网 时间:2024/06/07 10:23
def deco(func):    def _deco():        print("before myfunc called.")        func()        print("after myfunc called.")    return _deco@deco  #相当于执行myfunc = deco(myfunc),把myfunc变成了deco定义的_deco()函数def myfunc():    print("myfunc() called.")myfunc()myfunc()
# -*- coding:gbk -*-'''示例8: 装饰器带类参数'''class locker:    def __init__(self):        print("locker.__init__() should be not called.")    @staticmethod    def acquire():        print("locker.acquire() called.(这是静态方法)")    @staticmethod    def release():        print("  locker.release() called.(不需要对象实例)")def deco(cls):    '''cls 必须实现acquire和release静态方法'''    def _deco(func):        def __deco():            print("before %s called [%s]." % (func.__name__, cls))            cls.acquire()            try:                return func()            finally:                cls.release()        return __deco    return _deco@deco(locker)def myfunc():    print(" myfunc() called.")myfunc()myfunc()

比如:多个decorator

1
2
3
4
@decorator_one
@decorator_two
def func():
    pass

相当于:

1
func = decorator_one(decorator_two(func))

比如:带参数的decorator:

1
2
3
@decorator(arg1, arg2)
def func():
    pass

相当于:

1
func = decorator(arg1,arg2)(func)

这意味着decorator(arg1, arg2)这个函数需要返回一个“真正的decorator”。

内置的装饰器有三个,分别是staticmethod、classmethod和property,作用分别是把类中定义的实例方法变成静态方法、类方法和类属性。
参考链接:http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html
原创粉丝点击