What is a python decorator?
Network definition:
The decorator is a function used to wrap the function. It is used to modify the original function, assign it to the original identifier, and permanently remove the reference of the original function.
The following is an example of a decorator:
Copy codeThe Code is as follows:
#-*-Coding: UTF-8 -*-
Import time
Def foo ():
Print 'in foo ()'
# Define a timer, input one, and return another method with the timer function attached
Def timeit (func ):
# Define an embedded packaging function to pack the input function with the timing Function
Def wrapper ():
Start = time. clock ()
Func ()
End = time. clock ()
Print 'used: ', end-start
# Return the packaged Function
Return wrapper
Foo = timeit (foo)
Foo ()
Python provides a @ symbol syntax sugar to simplify the above Code. They play the same role.
Copy codeThe Code is as follows:
Import time
Def timeit (func ):
Def wrapper ():
Start = time. clock ()
Func ()
End = time. clock ()
Print 'used: ', end-start
Return wrapper
@ Timeit
Def foo ():
Print 'in foo ()'
Foo ()
The two sections of code are the same and equivalent.
The three built-in decorators are staticmethod, classmethod, and property. Their role is to convert the methods defined in the class into static methods, class methods, and attributes as follows:
Copy codeThe Code is as follows:
Class Rabbit (object ):
Def _ init _ (self, name ):
Self. _ name = name
@ Staticmethod
Def newRabbit (name ):
Return Rabbit (name)
@ Classmethod
Def newRabbit2 (cls ):
Return Rabbit ('')
@ Property
Def name (self ):
Return self. _ name
Nest of the decorator:
Just one rule: the nesting order is the opposite of the code order.
Let's also look at an example:
Copy codeThe Code is as follows:
#! /Usr/bin/python
#-*-Coding: UTF-8 -*-
Def makebold (fn ):
Def wrapped ():
Return "<B>" + fn () + "</B>"
Return wrapped
Def makeitalic (fn ):
Def wrapped ():
Return "<I>" + fn () + "</I>"
Return wrapped
@ Makebold
@ Makeitalic
Def hello ():
Return "hello world"
Print hello ()
The returned result is:
<B> <I> hello world </I> </B>
Why is this result?
1. First, the hello function is decorated by the makeitalic function and becomes the result <I> hello world </I>
2. After the decoration of the makebold function, it becomes <B> <I> hello world </I> </B>, which is easy to understand.