python@九步裝飾器

來源:互聯網
上載者:User

標籤:

這是在Python學習小組上介紹的內容,現學現賣、多練習是好的學習方式。

第一步:最簡單的函數,準備附加額外功能

?

1

2

3

4

5

6

7

8

# -*- coding:gbk -*-

‘‘‘樣本1: 最簡單的函數,表示調用了兩次‘‘‘

 

defmyfunc():

    print("myfunc() called.")

 

myfunc()

myfunc()

 

第二步:使用裝飾函數在函數執行前和執行後分別附加額外功能

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

# -*- coding:gbk -*-

‘‘‘樣本2: 替換函數(裝飾)

裝飾函數的參數是被裝飾的函數對象,返回原函數對象

裝飾的實質語句: myfunc = deco(myfunc)‘‘‘

 

defdeco(func):

    print("before myfunc() called.")

    func()

    print("  after myfunc() called.")

    returnfunc

 

defmyfunc():

    print(" myfunc() called.")

 

myfunc=deco(myfunc)

 

myfunc()

myfunc()

第三步:使用文法糖@來裝飾函數

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

# -*- coding:gbk -*-

‘‘‘樣本3: 使用文法糖@來裝飾函數,相當於“myfunc = deco(myfunc)”

但發現新函數只在第一次被調用,且原函數多調用了一次‘‘‘

 

defdeco(func):

    print("before myfunc() called.")

    func()

    print("  after myfunc() called.")

    returnfunc

 

@deco

defmyfunc():

    print(" myfunc() called.")

 

myfunc()

myfunc()

第四步:使用內嵌封裝函數來確保每次新函數都被調用

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

# -*- coding:gbk -*-

‘‘‘樣本4: 使用內嵌封裝函數來確保每次新函數都被調用,

內嵌封裝函數的形參和傳回值與原函數相同,裝飾函數返回內嵌封裝函數對象‘‘‘

 

defdeco(func):

    def_deco():

        print("before myfunc() called.")

        func()

        print("  after myfunc() called.")

        # 不需要返回func,實際上應返回原函數的傳回值

    return_deco

 

@deco

defmyfunc():

    print(" myfunc() called.")

    return‘ok‘

 

myfunc()

myfunc()

第五步:對帶參數的函數進行裝飾

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

# -*- coding:gbk -*-

‘‘‘樣本5: 對帶參數的函數進行裝飾,

內嵌封裝函數的形參和傳回值與原函數相同,裝飾函數返回內嵌封裝函數對象‘‘‘

 

defdeco(func):

    def_deco(a, b):

        print("before myfunc() called.")

        ret=func(a, b)

        print("  after myfunc() called. result: %s"%ret)

        returnret

    return_deco

 

@deco

defmyfunc(a, b):

    print(" myfunc(%s,%s) called."%(a, b))

    returna+b

 

myfunc(1,2)

myfunc(3,4)

第六步:對參數數量不確定的函數進行裝飾

?

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

# -*- coding:gbk -*-

‘‘‘樣本6: 對參數數量不確定的函數進行裝飾,

參數用(*args, **kwargs),自動適應變參和具名引數‘‘‘

 

defdeco(func):

    def_deco(*args,**kwargs):

        print("before %s called."%func.__name__)

        ret=func(*args,**kwargs)

        print("  after %s called. result: %s"%(func.__name__, ret))

        returnret

    return_deco

 

@deco

defmyfunc(a, b):

    print(" myfunc(%s,%s) called."%(a, b))

    returna+b

 

@deco

defmyfunc2(a, b, c):

    print(" myfunc2(%s,%s,%s) called."%(a, b, c))

    returna+b+c

 

myfunc(1,2)

myfunc(3,4)

myfunc2(1,2,3)

myfunc2(3,4,5)

第七步:讓裝飾器帶參數

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

# -*- coding:gbk -*-

‘‘‘樣本7: 在樣本4的基礎上,讓裝飾器帶參數,

和上一樣本相比在外層多了一層封裝。

裝飾函數名實際上應更有意義些‘‘‘

 

defdeco(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")

defmyfunc():

    print(" myfunc() called.")

 

@deco("module2")

defmyfunc2():

    print(" myfunc2() called.")

 

myfunc()

myfunc2()

第八步:讓裝飾器帶 類 參數

?

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: 裝飾器帶類參數‘‘‘

 

classlocker:

    def__init__(self):

        print("locker.__init__() should be not called.")

         

    @staticmethod

    defacquire():

        print("locker.acquire() called.(這是靜態方法)")

         

    @staticmethod

    defrelease():

        print("  locker.release() called.(不需要對象執行個體)")

 

defdeco(cls):

    ‘‘‘cls 必須實現acquire和release靜態方法‘‘‘

    def_deco(func):

        def__deco():

            print("before %s called [%s]."%(func.__name__,cls))

            cls.acquire()

            try:

                returnfunc()

            finally:

                cls.release()

        return__deco

    return_deco

 

@deco(locker)

defmyfunc():

    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‘‘‘

 

classmylocker:

    def__init__(self):

        print("mylocker.__init__() called.")

         

    @staticmethod

    defacquire():

        print("mylocker.acquire() called.")

         

    @staticmethod

    defunlock():

        print("  mylocker.unlock() called.")

 

classlockerex(mylocker):

    @staticmethod

    defacquire():

        print("lockerex.acquire() called.")

         

    @staticmethod

    defunlock():

        print("  lockerex.unlock() called.")

 

deflockhelper(cls):

    ‘‘‘cls 必須實現acquire和release靜態方法‘‘‘

    def_deco(func):

        def__deco(*args,**kwargs):

            print("before %s called."%func.__name__)

            cls.acquire()

            try:

                returnfunc(*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檔案中

同時示範了對一個函數應用多個裝飾器‘‘‘

 

frommylockerimport*

 

classexample:

    @lockhelper(mylocker)

    defmyfunc(self):

        print(" myfunc() called.")

 

    @lockhelper(mylocker)

    @lockhelper(lockerex)

    defmyfunc2(self, a, b):

        print(" myfunc2() called.")

        returna+b

 

if__name__=="__main__":

    a=example()

    a.myfunc()

    print(a.myfunc())

    print(a.myfunc2(1,2))

    print(a.myfunc2(3,4))

[email protected]九步裝飾器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.