Python Road-Decorators

Source: Internet
Author: User

Definition: An adorner is essentially a function that is used to decorate other functions (that is, adding additional functionality to other functions):
    1. Cannot modify the source code of the decorated function
    2. Cannot modify the calling method of the decorated function
Decorator Preparation Knowledge:
    1. Function name is "variable"
    2. Higher order functions
      1. Pass a function name as an argument to another function (add a function to it without modifying the source code of the decorated function)
      2. The return value contains the function name (does not modify the function's Calling method)
    3. Nested functions
    4. Higher order function + nested function = = Adorner
Example:
#!usr/bin/env python#-*-coding:utf-8-*-import timedef Deco (func): Def wrapper (*args,**kwargs): #*args,**kwargs Can implement MyFunc outgoing arbitrary parameters start_time = Time.time () res = func (*args,**kwargs) end_time = Time.time () pr Int ("Elapsed time%s"% (end_time-start_time)) return res #如果func有返回值那么将其返回 return wrapper @deco #等价于 MYF UNC = Deco (MYFUNC) If you want to think about other parameters in the adorner, you can pass in the parameters such as deco ("xxx") after Deco, and the adorner will add a function nesting, and the parameters passed through Deco should be at the outermost layer, decorator ("XXX" ) def myfunc (): Time.sleep (3) print ("in MyFunc") MyFunc ()

Python Road-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.