Python学习之装饰器

参考;http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html


# coding=utf-8_

_author__ = "leaves"
# 装饰器
# 使用装饰函数在函数执行钱和执行后分别附加额外功能
print "使用装饰函数在函数执行钱和执行后分别附加额外功能"




def deco(func):
    print ('before myfucn() called.')
    func()
    print ('after myfunc() called')
    return func




def myfunc():
    print ('myfunc() called')




myfunc = deco(myfunc)
myfunc()


# 使用语法@来装饰函数
print "使用语法@来装饰函数"




def deco(func):
    print ('before myfucn() called.')
    func()
    print ('after myfunc() called')
    return func




@deco
def myfunc():
    print ('myfunc() called')




myfunc()


# 使用内嵌包装函数来确保每次新函数都被调用
print "使用内嵌包装函数来确保每次新函数都被调用"




def deco(func):
    def _deco():
        print ('before myfucn() called.')
        func()
        print ('after myfunc() called')


    return _deco




@deco
def myfunc():
    print ('myfunc() called')
    return 'ok'




myfunc()


# 对带参数的函数进行装饰
print "对带参数的函数进行装饰"




def deco(func):
    def _deco(a, b):
        print ('before myfucn() called.')
        func(a, b)
        print ('after myfunc() called')


    return _deco




@deco
def myfunc(a, b):
    print ("myfunc(%s,%s) called." % (a, b))
    return 'ok'




myfunc(1, 2)


# 对参数数量不确定的函数进行装饰
print "对参数数量不确定的函数进行装饰"




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 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 ("myfunc(%s,%s, %s) called." % (a, b, c))
    return a + b + c




myfunc(1, 2)
myfunc2(1, 2, 3)


# 让装饰器带参数
print "让装饰器带参数"




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("mymodule2")
def myfunc2():
    print ("myfunc() called.")




myfunc()
myfunc2()


# 让装饰器带 类 参数
print "让装饰器带 类 参数"




class locker:
    def __init__(self):
        print ("locker.__init__() should be not called.")


    @staticmethod
    def acquire():
        print ("locker.acquier() called.(这是静态方法)")


    @staticmethod
    def release():
        print ("locker.release() called.(不需要对象实例)")




def deco(cls):
    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()


# 装饰器带类参数,并分拆公共类到其他py文件中,同时演示了对一个函数应用多个装饰器
print "装饰器带类参数,并分拆公共类到其他py文件中,同时演示了对一个函数应用多个装饰器"


from mylocker import *




class example:
    @lockhelper(mylocker)
    def myfunc(self):
        print("myfunc() called")


    @lockhelper(mylocker)
    @lockhelper(lockerex)
    def myfunc2(self, a, b):
        print("myfunc2() called.")
        return a + b




if __name__ == "__main__":
    a = example()
    # a.myfunc()
    print (a.myfunc())
    print (a.myfunc2(1, 2))

    print (a.myfunc2(3, 4))


引用文件

# coding=utf-8_
_author__ = "leaves"




class mylocker:
    def __init__(self):
        print("mylocker.__init__() called.")


    @staticmethod
    def acquire():
        print("mylocker.acquire() called.")


    @staticmethod
    def unlock():
        print("  mylocker.unlock() called.")




class lockerex(mylocker):
    @staticmethod
    def acquire():
        print("lockerex.acquire() called.")


    @staticmethod
    def unlock():
        print("  lockerex.unlock() called.")




def lockhelper(cls):
    '''cls 必须实现acquire和release静态方法'''


    def _deco(func):
        def __deco(*args, **kwargs):


            print("before %s called." % func.__name__)
            cls.acquire()
            try:
                return func(*args, **kwargs)
            finally:
                cls.unlock()


        return __deco


    return _deco


输出:


"D:\Program Files\Python\python.exe" G:/HelloPython/list/deco.py
使用装饰函数在函数执行钱和执行后分别附加额外功能
before myfucn() called.
myfunc() called
after myfunc() called
myfunc() called
使用语法@来装饰函数
before myfucn() called.
myfunc() called
after myfunc() called
myfunc() called
使用内嵌包装函数来确保每次新函数都被调用
before myfucn() called.
myfunc() called
after myfunc() called
对带参数的函数进行装饰
before myfucn() called.
myfunc(1,2) called.
after myfunc() called
对参数数量不确定的函数进行装饰
before myfunc called.
myfunc(1,2) called.
after myfunc called.result = 3
before myfunc2 called.
myfunc(1,2, 3) called.
after myfunc2 called.result = 6
让装饰器带参数
before myfunc called [mymodule].
myfunc( called.
after myfunc called [mymodule].
before myfunc2 called [mymodule2].
myfunc() called.
after myfunc2 called [mymodule2].
让装饰器带 类 参数
before myfunc called [__main__.locker].
locker.acquier() called.(这是静态方法)
myfunc() called.
locker.release() called.(不需要对象实例)
装饰器带类参数,并分拆公共类到其他py文件中,同时演示了对一个函数应用多个装饰器
before myfunc called.
mylocker.acquire() called.
myfunc() called
  mylocker.unlock() called.
None
before __deco called.
mylocker.acquire() called.
before myfunc2 called.
lockerex.acquire() called.
myfunc2() called.
  lockerex.unlock() called.
  mylocker.unlock() called.
3
before __deco called.
mylocker.acquire() called.
before myfunc2 called.
lockerex.acquire() called.
myfunc2() called.
  lockerex.unlock() called.
  mylocker.unlock() called.
7


Process finished with exit code 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值