Python function Adorner usage examples

Source: Internet
Author: User
This example describes the Python function adorner usage. Share to everyone for your reference. Specific as follows:

Adorners are often used for scenes with cut-off requirements, with more classic insert logs, performance tests, transaction processing, and more. Decorators are a great design for solving this kind of problem,
With adorners, we can pull out a lot of the same code that has nothing to do with function itself and continue to reuse it. In summary, the function of an adorner is to add additional functionality to an already existing object.

#! Coding=utf-8 Import Time Def Timeit (func):   def Wrapper (a):     start = Time.clock ()     func     end = Time.clock ()     print ' used: ', End-start     print a   return wrapper @timeit # foo = Timeit (foo) is exactly equivalent, # after use, the Foo function changes , equivalent to the Def foo (A, b):   pass #不带参数的装饰器 # Wraper to decorate the FN, return Wraper, the Wraper returned is the decorated FN def test (func):   de F Wraper ():     print "Test start"     func ()     print "End Start"   return wraper @test def foo ():   

Output:

The adorner modifies the function with parameters:

def parameter_test (func):   def wraper (a):     print "Test start"     func (a)     print "End Start"   return Wraper @parameter_test def Parameter_foo (a):   

Output:

A function that decorates an indeterminate number of parameters:

def much_test (func):   def wraper (*args, **kwargs):     print "Test start"     func (*args, **kwargs)     print "End Start "   return wraper @much_test def much1 (a):   print a @much_test def much2 (a,b,c,d):   

Output:

With the parameters of the adorner, and then one layer will be able to:

def TP (Name,age):   def much_test (func):     print ' in Much_test '     def wraper (*args, **kwargs):       print "test Start "       print str (name), ' at: ' +str (age)       func (*args, **kwargs)       print" End Start "     return Wraper   return much_test @tp (' One ', ' ten ') def tptest (parameter):   

Output:

Class Locker:   def __init__ (self):     print ("locker.__init__ () should is not called.")   @staticmethod   def acquire ():     print ("Locker.acquire () called. (This is a static method)")   @staticmethod   def release ( ):     Print ("Locker.release () called. (no object instance required") def deco (CLS):   "The CLS must implement the acquire and release static method '   def _deco (func):     def __deco ():       print ("before%s called [%s]."% (func.__name__, CLS))       Cls.acquire ()       try:         return func ()       finally:         cls.release ()     return __deco   return _deco @deco (locker) def MyFunc () :   

Output:

Class Mylocker:def __init__ (self): print ("mylocker.__init__ () called.")   @staticmethod def acquire (): Print ("Mylocker.acquire () called.") @staticmethod def unlock (): Print ("Mylocker.unlock () called.") class Lockerex (Mylocker): @staticmethod def acqu   IRE (): Print ("Lockerex.acquire () called.") @staticmethod def unlock (): Print ("Lockerex.unlock () called.") def Lockhelper (CLS): "The CLS must implement acquire and release static parties Law ' def _deco (func): Def __deco (*args, **kwargs): Print ("before%s called."% func.__name__) Cls.acquir E () Try:return func (*args, **kwargs) Finally:cls.unlock () return __deco return _deco C   Lass Example: @lockhelper (Mylocker) def myfunc (self): print ("MyFunc () called.")     @lockhelper (Mylocker) @lockhelper (Lockerex) def myfunc2 (self, A, b): Print ("Myfunc2 () called.") Return a + b if __name__== "__main__": A = Example () A.myfunc () print (A.myfunc ()) Print (A.MYFUNC2 (1, 2)) Print (A.MYFUNC2 (3, 4)) 

Output:

Before MyFunc Called.mylocker.acquire () called. MyFunc () called. Mylocker.unlock () Called.before myfunc called.mylocker.acquire () called. MyFunc () called. Mylocker.unlock () called. Nonebefore __deco called.mylocker.acquire () Called.before myfunc2 Called.lockerex.acquire () called. MYFUNC2 () called. Lockerex.unlock () called. Mylocker.unlock () Called.3before __deco called.mylocker.acquire () Called.before myfunc2 Called.lockerex.acquire () Called. MYFUNC2 () called. Lockerex.unlock () called. Mylocker.unlock () Called.7

Hopefully this article will help you with Python programming.

  • 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.