Learn to organize--python decorators

Source: Internet
Author: User

Usage scenarios:

Think of the question: How can you add new functionality to the original module for a production system, with minimal modifications? This can be accomplished with the adorner.

The adorner has two standards:

1, do not modify the original code and the original call mode;

2, can add new functions;

For example, we have a method func1, in which we print two messages and sleep for 1 seconds.

Def func1 ():
Print ("This was inthe func1 Methord")
Time.sleep (1)
Print ("exec the func1 finished")

' Call method '
if __name__ = = "__main__":
Func1 ()

Now I want to not modify the Func1 () method and how to invoke the premise, add a print the current time of the function, how to implement it?

Import time

def Timmer (func):#Defining adornersTimmer
def decotator (*args,**kwargs):#Defining higher order functions
PrintDecorator,and Current time is%s ", Args,kwargs)#The method added
Func (*args,**kwargs)#To execute a method of passing a variable
Return Decotator#It returns the higher-order function address

@timmer#Indicates that the adorner isTimmer, equivalent toFunc1=timmer (FUNC1)
Def func1 ():
Print"This was in the Func1 Methord")
Time.sleep (1)
print ("exec the func1 finished")

@timmer
def FUNC2 (name):
print ("Func2 Methord,and The name is:%s"%name)
Time.sleep (1)
print ("exec the Func2 finished")



# Call the func1 method
Func1 ()

Learn to organize--python decorators

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.