python--Decorator

Source: Internet
Author: User

1, the role of the adorner

The role of adorners is to add additional functionality to objects that already exist. Adorners are used to decorate functions or classes, using adorners to add actions before and after a function is executed

For example, first define a function that doesn't work, just print out a string

1 def foo (): 2     Print (' hello ') 3 4 foo ()     #输出你好

Now let's enrich the functionality of this function

1 deffoo1 ():2Before=input ("Enter the person you want to greet:")3In_str="Hello"4     Print("{0},{1}". Format (BEFORE,IN_STR))5after ="Goodbye"6     Print("{0},{1}". Format (before,after))7 8Foo1 () #输出: xx Hello, xx goodbye

Because the programming language follows the principle of open and closed, if the first function is already written in the company's underlying code, then do not allow the random changes, then we can not change the original underlying code, then like the 2nd function, the original underlying function is arbitrarily modified, the general company will not do so, Then you can use the adorner to add some new functionality to the original function, the following FOO2 () function implements the same function as the foo1 () function, and does not modify the original underlying code

1 defFoo2 (func):#Here you can pass the original Foo function as a parameter2 3     deffoo1 ():4before = input ("Enter the person you want to greet:")5 6R=func ()7         returnR#returns the contents of the PrintOut in Foo ()8         Print("{0},{1}". Format (before, R))9 Tenafter ="Goodbye" One         Print("{0},{1}". Format (before, after)) A  -     returnFoo1#returns the contents of the FOO1 function -  theFoo2 (foo)

python--Decorator

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.