Before you know the adorner, be sure to understand the function as a parameter pass, what is the function inline, please refer to my previous blog function introduction
The Python decorator idea is somewhat similar to the decorative pattern of the design pattern, with the intention of dynamically adding additional functionality to the function object. Like the ability to add log printing, it's a bit of a facet-oriented programming (AOP) feeling.
Adorner syntax
Begins with @, followed by the adorner's name and optional parameters. Decorator syntax is a syntactic sugar.
The format is as follows
@decomaker(deco_args) def foo(func_opt_args)
Can be combined, equivalent to Foo = g (f (foo))
@g@fdef foo(): statement
Simple decorator
Instance
#!/usr/bin/pythondef deco(func): print‘start‘ func() print‘end‘ return func@decodef foo(): print‘In foo‘foo()foo()
Output
startIn fooendIn fooIn foo
With inline function adorner
Inline function guarantees that each new function is called
Instance
def deco(func): def _deco(): #该函数为内嵌函数 print‘start‘ func() print‘end‘ return _deco@decodef foo(): print‘In foo‘foo()foo()
Output:
startIn fooendstartIn fooend
Adorner with parameters
You need to return the adorner with the function as a parameter. In other words, Decomaker () did something with Deco_args and returned
A function object, which is an adorner with Foo as its argument. Simply put: foo = Decomaker (Deco_args) (foo)
Instance
defdeco(ARG): def wrapper(func): def _deco(x): Print "Get param is:", x func (x)return_decoreturnWrapper@deco ("type1") def foo(x): Print ' in foo 'Foo123)
Output
getis: 123In foo
Introduction to Python Decorators