Examples of python function decorator usage and python function examples

Source: Internet
Author: User
Tags function examples

Examples of python function decorator usage and python function examples

This document describes how to use the python function decorator. Share it with you for your reference. The details are as follows:

The decorator is often used in scenarios with cut-plane requirements. More typical scenarios include log insertion, performance testing, and transaction processing. The decorator is an excellent design for solving such problems,
With the decorator, we can extract a large number of identical codes irrelevant to the function itself and continue to reuse them. In summary, the purpose of the decorator is to add additional functions to existing objects.

#! Coding = UTF-8 import time def timeit (func): def wrapper (a): start = time. clock () func (1, 2) 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 wrapper: def foo (a, B): pass # decorator without parameters # wraper will decorate fn, return wraper, the returned wraper is the decorated fn def test (func): def wraper (): print "test start" func () print "end start" return wraper @ test foo (): print "in foo" foo ()

Output:

test start in foo end start 

Modifier 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):   print "parameter_foo:"+a #parameter_foo('hello') 

Output:

>>> test start parameter_foo:hello end start 

Modifier:

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 ):   print a,b,c,d much1('a') much2(1,2,3,4) 

Output:

test start a end start test start 1 2 3 4 end start 

You can package another layer of decorator with parameters:

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','10') def tpTest(parameter):   print parameter tpTest('python....') 

Output:

in much_test test start one at:10 python.... end start 
Class locker: def _ init _ (self): print ("locker. _ init _ () shoshould be not called. ") @ staticmethod def acquire (): print (" locker. acquire () called. (This is a static method) ") @ staticmethod def release (): print (" locker. release () called. (object instance not required ") def deco (cls): ''' cls must implement the acquire and release static methods ''' def _ deco (func): def _ deco (): print ("before % s called [% s]. "% (func. _ name __, cls) cls. acquire () try: return func () finally: cls. release () return _ deco @ deco (locker) def myfunc (): print ("myfunc () called. ") myfunc ()

Output:

>>> Before myfunc called [_ main __. locker]. locker. acquire () called. (This is a static method) myfunc () called. locker. release () called. (object instances are not required>
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 acquire (): print (" lockerex. acquire () called. ") @ staticmethod def unlock (): print (" lockerex. unlock () called. ") def lockhelper (cls): ''' cls must implement the acquire and release static methods ''' def _ deco (func): def _ deco (* args, ** kwargs): print ("before % s called. "% func. _ name _) cls. acquire () try: return func (* args, ** kwargs) finally: cls. unlock () return _ deco class 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 (). myfunc () print (. myfunc () print (. myfunc2 (1, 2) print (. 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

I hope 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.