Introduction to Python Decorators

Source: Internet
Author: User
Tags python decorator

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

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.