What is a python decorator?
Definitions on the network:
An adorner is a function that wraps a function, modifies the original function, assigns it to the original identifier, and permanently loses the reference to the original function.
The most illustrative examples of adorners are as follows:
Copy Code code as follows:
#-*-Coding:utf-8-*-
Import time
def foo ():
print ' in foo () '
# define a timer, pass in one, and return another method with the timer function attached
def Timeit (func):
# defines an inline wrapper function that adds the timer function to the incoming function.
def wrapper ():
Start = Time.clock ()
Func ()
End =time.clock ()
print ' used: ', End-start
# returns the Wrapped function back
Return wrapper
foo = Timeit (foo)
Foo ()
Python provides an @ symbol for the syntax of sugar, to simplify the code above, their role is the same
Copy Code code 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 code for these 2 paragraphs is the same, equivalent.
The built-in 3 adorners, respectively, are staticmethod,classmethod,property, and their role is to transform the methods defined in the class into static methods, class methods, and properties, as follows:
Copy Code code 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
Nesting of adorners:
One rule: The order of nesting and the order of code are the opposite.
Also take a look at an example:
Copy Code code 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 to "Hello World"
Print Hello ()
The result returned is:
<b><i>hello world</i></b>
Why is this result?
1. First the Hello function is decorated with the makeitalic function, which becomes the result <i>hello world</i>
2. Then after the Makebold function of decoration, into the <b><i>hello World</i></b>, this understanding is very simple.