首页 > 代码库 > python装饰器1

python装饰器1

第八步:让装饰器带 类 参数

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

# -*- 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()

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

# -*- coding:gbk -*-

‘‘‘mylocker.py: 公共类 for 示例9.py‘‘‘

 

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

# -*- coding:gbk -*-

‘‘‘示例9: 装饰器带类参数,并分拆公共类到其他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))

下面是参考资料,当初有不少地方没看明白,真正练习后才明白些:

1. Python装饰器学习 http://blog.csdn.net/thy38/article/details/4471421

2. Python装饰器与面向切面编程 http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html

3. Python装饰器的理解 http://apps.hi.baidu.com/share/detail/17572338

python装饰器1