Python function decorator usage example

Source: Internet
Author: User

Python function decorator usage example

This document describes how to use the python function decorator. Share it with you for your reference. The details are as follows:

The decorator is often used in scenarios with cut-plane requirements. More typical scenarios include log insertion, performance testing, and transaction processing. The decorator is an excellent design for solving such problems,

With the decorator, we can extract a large number of identical codes irrelevant to the function itself and continue to reuse them. In summary, the purpose of the decorator is to add additional functions to existing objects.

?

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

#! Coding = UTF-8

Import time

Def timeit (func ):

Def wrapper ():

Start = time. clock ()

Func (1, 2)

End = time. clock ()

Print 'used: ', end-start

Print

Return wrapper

@ Timeit

# Foo = timeit (foo) is equivalent,

# After use, the foo function changes, which is equivalent to wrapper.

Def foo (a, B ):

Pass

# Decorator without Parameters

# Wraper will decorate fn, return wraper, and return wraper is the fn after decoration

Def test (func ):

Def wraper ():

Print "test start"

Func ()

Print "end start"

Return wraper

@ Test

Def foo ():

Print "in foo"

Foo ()

Output:

?

1

2

3

Test start

In foo

End start

Modifier with parameters:

?

1

2

3

4

5

6

7

8

9

10

Def parameter_test (func ):

Def wraper ():

Print "test start"

Func ()

Print "end start"

Return wraper

@ Parameter_test

Def parameter_foo ():

Print "parameter_foo:" +

# Parameter_foo ('hello ')

Output:

?

1

2

3

4

>>>

Test start

Parameter_foo: hello

End start

Modifier:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Def much_test (func ):

Def wraper (* args, ** kwargs ):

Print "test start"

Func (* args, ** kwargs)

Print "end start"

Return wraper

@ Much_test

Def much1 ():

Print

@ Much_test

Def much2 (a, B, c, d ):

Print a, B, c, d

Muyun ('A ')

Much2 (1, 2, 3, 4)

Output:

?

1

2

3

4

5

6

Test start

A

End start

Test start

1 2 3 4

End start

You can package another layer of decorator with parameters:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Def tp (name, age ):

Def much_test (func ):

Print 'in much_test'

Def wraper (* args, ** kwargs ):

Print "test start"

Print str (name), 'at: '+ str (age)

Func (* args, ** kwargs)

Print "end start"

Return wraper

Return much_test

@ Tp ('one', '10 ')

Def tpTest (parameter ):

Print parameter

TpTest ('python ....')

Output:

?

1

2

3

4

5

In much_test

Test start

One at: 10

Python ....

End start

?

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

Class locker:

Def _ init _ (self ):

Print ("locker. _ init _ () shocould be not called .")

@ Staticmethod

Def acquire ():

Print ("locker. acquire () called. (This is a static method )")

@ Staticmethod

Def release ():

Print ("locker. release () called. (object instance not required ")

Def deco (cls ):

''' Cls must implement the acquire and release static methods '''

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

Output:

?

1

2

3

4

5

6

>>>

Before myfunc called [_ main _. locker].

Locker. acquire () called. (This is a static method)

Myfunc () called.

Locker. release () called. (The object instance is not required.

>>>

?

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

37

38

39

40

41

42

43

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 must implement the acquire and release static methods '''

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

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

Output:

?

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

Before myfunc called.

Mylocker. acquire () called.

Myfunc () called.

Mylocker. unlock () called.

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

I hope this article will help you with Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.