Python advanced programming-part3 Decorator Prelude

Source: Internet
Author: User
Tags shallow copy

Decorators are used to wrap functions, add extra functionality, and should be able to decorate a batch of functions to reduce code reuse.

a simple decorator

A function receives a function object as a parameter and returns a function object, such that a function can become a decorator, as defined below:

def deco (func): Def _deco (*args): print "Do Something" func (*args) return _deco

In the above decorator, Func is called the modified function, and some additional initialization is done before the Func is executed.

After the decorator definition is complete, use @ To modify the function, as shown here:

@deco #实际相当于执行了f = Deco (f) def f (x): Print X

After the above processing, view F's function name has become "_deco"

Print Fprint deco (f)

The operating result is:

<function _deco at 0x00000000022314a8>
<function _deco at 0x0000000002231518>

After the description finishes, F is the shallow copy version of Deco (f).

Then, when we call F ("Hello"), we get the following output:

Do something
Hello


Modifiers with parameters

Decorator is a function form, of course, you can pass in parameters, at this point, you must add a layer of nested to receive parameters, as follows:

Def deco_args (a, b):               # a,b is the parameter     def deco (func) required by the decorator:         def _deco (*args):          # * Args is the parameter required for the function being wrapped             print  "do  Something "            func (*args)               #do  something         return _deco    return deco                    #  closures are required for @deco_args ( )                     #  equivalent to F = deco_args (f) def f (x):      print x 


This article is from the "Nameless" blog, please be sure to keep this source http://xdzw608.blog.51cto.com/4812210/1603620

Python advanced programming-part3 Decorator Prelude

Related Article

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.