Introduction to Python (vi) understanding of adorners

Source: Internet
Author: User

A function of the adorner used to extend the function of the original function
Like what:

def helloWorld(fun)        def out()                print ("======start========")                fun()                print ("=====end======")        return out@helloWorlddef back ()        print ("let‘s go")back()

Operation Result:

======start========let‘s go=====end======

The br/>@ symbol is the syntactic sugar of the adorner, which is used when defining the function and avoids the assignment of the value again.

Run step def back () →return out→def out ()
Adorner with parameters:

def helloWorld(arg):        def out(fun):                def go():                        print ("======start========")                        fun()                        print ("=====end======")                return go               return out@helloWorld("will‘)def back ():        print ("let‘s go")back()

Operation Result:

======start========let‘s go=====end======

See the adorner comes in with a parameter, then the running process of this parameter will be run, the overall operation of the process

When a function is also involved with parameters:

def logging(taskname):    def wrapper(func):        def retu(*args, **wkargs):            # 函数通过装饰起参数给装饰器传送参数            print (‘before task‘,taskname)            # 装饰器传变量给函数            taskid = 1            summer, funcres = func(taskid, *args, **wkargs)            print (‘after task‘, taskid, summer)        return retu    return wrapper@logging("test")def testd(taskid):    print ("testd runing",taskid)    return "task summer success eg",[]testd()

Run the results and steps:

Introduction to Python (vi) understanding of adorners

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.