Python decorator use example and actual application example, python example

Source: Internet
Author: User
Tags python decorator

Python decorator use example and actual application example, python example

Test 1

Deco is running, but myfunc is not running

Copy codeThe Code is as follows:
Def deco (func ):
Print 'before func'
Return func

Def myfunc ():
Print 'myfunc () called'
 
Myfunc = deco (myfunc)

Test 2

Call myfunc in the required deco to execute
Copy codeThe Code is as follows:
Def deco (func ):
Print 'before func'
Func ()
Print 'after func'
Return func

Def myfunc ():
Print 'myfunc () called'
 
Myfunc = deco (myfunc)

Test 3

@ Function name, but it is executed twice

Copy codeThe Code is as follows:
Def deco (func ):
Print 'before func'
Func ()
Print 'after func'
Return func

@ Deco
Def myfunc ():
Print 'myfunc () called'

Myfunc ()

Test 4

This decoration is required.

Copy codeThe Code is as follows:
Def deco (func ):
Def _ deco ():
Print 'before func'
Func ()
Print 'after func'
Return _ deco

@ Deco
Def myfunc ():
Print 'myfunc () called'
 
Myfunc ()

Test 5

@ Use nested methods with Parameters
Copy codeThe Code is as follows:
Def deco (arg ):
Def _ deco (func ):
Print arg
Def _ deco ():
Print 'before func'
Func ()
Print 'after func'
Return _ deco
Return _ deco

@ Deco ('Demo ')
Def myfunc ():
Print 'myfunc () called'
 
Myfunc ()

Test 6

Function parameter transfer
Copy codeThe Code is as follows:
Def deco (arg ):
Def _ deco (func ):
Print arg
Def _ deco (str ):
Print 'before func'
Func (str)
Print 'after func'
Return _ deco
Return _ deco

@ Deco ('Demo ')
Def myfunc (str ):
Print 'myfunc () called', str
 
Myfunc ('hello ')

Test 7

Number of unknown parameters
Copy codeThe Code is as follows:
Def deco (arg ):
Def _ deco (func ):
Print arg
Def _ deco (* args, ** kwargs ):
Print 'before func'
Func (* args, ** kwargs)
Print 'after func'
Return _ deco
Return _ deco

@ Deco ('decode1 ')
Def myfunc1 (str ):
Print 'myfunc1 () called', str

@ Deco ('demo2 ')
Def myfunc2 (str1, str2 ):
Print 'myfunc2 () called', str1, str2
 
Myfunc1 ('hello ')
 
Myfunc2 ('hello', 'World ')

Test 8

Class As Modifier
Copy codeThe Code is as follows:
Class myDecorator (object ):
 
Def _ init _ (self, fn ):
Print "inside myDecorator. _ init __()"
Self. fn = fn
 
Def _ call _ (self ):
Self. fn ()
Print "inside myDecorator. _ call __()"
 
@ MyDecorator
Def aFunction ():
Print "inside aFunction ()"
 
Print "Finished decorating aFunction ()"
 
AFunction ()

Test 9
Copy codeThe Code is as follows:
Class myDecorator (object ):
 
Def _ init _ (self, str ):
Print "inside myDecorator. _ init __()"
Self. str = str
Print self. str
 
Def _ call _ (self, fn ):
Def wrapped (* args, ** kwargs ):
Fn ()
Print "inside myDecorator. _ call __()"
Return wrapped
 
@ MyDecorator ('this is str ')
Def aFunction ():
Print "inside aFunction ()"
 
Print "Finished decorating aFunction ()"
 
AFunction ()

Instance

Caching functions-Fibonacci Series

Copy codeThe Code is as follows:
From functools import wraps
Def memo (fn ):
Cache = {}
Miss = object ()

@ Wraps (fn)
Def wrapper (* args ):
Result = cache. get (args, miss)
If result is miss:
Result = fn (* args)
Cache [args] = result
Return result
 
Return wrapper
 
@ Memo
Def fib (n ):
If n <2:
Return n
Return fib (n-1) + fib (n-2)

Print fib (10)

Register callback function-web Request callback

Copy codeThe Code is as follows:
Class MyApp ():
Def _ init _ (self ):
Self. func_map = {}
 
Def register (self, name ):
Def func_wrapper (func ):
Self. func_map [name] = func
Return func
Return func_wrapper
 
Def call_method (self, name = None ):
Func = self. func_map.get (name, None)
If func is None:
Raise Exception ("No function registered against-" + str (name ))
Return func ()
 
App = MyApp ()
 
@ App. register ('/')
Def main_page_func ():
Return "This is the main page ."
 
@ App. register ('/next_page ')
Def next_page_func ():
Return "This is the next page ."
 
Print app. call_method ('/')
Print app. call_method ('/next_page ')

Mysql encapsulation-Easy to use
Copy codeThe Code is as follows:
Import umysql
From functools import wraps
 
Class Organization aion:
Def _ init _ (self, env ):
If env = "Prod ":
Self. host = "coolshell.cn"
Self. port = 3306
Self. db = "coolshell"
Self. user = "coolshell"
Self. passwd = "fuckgfw"
Elif env = "Test ":
Self. host = 'localhost'
Self. port = 3300
Self. user = 'coolshell'
Self. db = 'coolshell'
Self. passwd = 'fuckgfw'
 
Def mysql (SQL ):
 
_ Conf = paiaion (env = "Prod ")
 
Def on_ SQL _error (err ):
Print err
Sys. exit (-1)
 
Def handle_ SQL _result (rs ):
If rs. rows> 0:
Fieldnames = [f [0] for f in rs. fields]
Return [dict (zip (fieldnames, r) for r in rs. rows]
Else:
Return []
 
Def decorator (fn ):
@ Wraps (fn)
Def wrapper (* args, ** kwargs ):
Mysqlconn = umysql. Connection ()
Mysqlconn. settimeout (5)
Mysqlconn. connect (_ conf. host, _ conf. port, _ conf. user ,\
_ Conf. passwd, _ conf. db, True, 'utf8 ')
Try:
Rs = mysqlconn. query (SQL ,{})
Failed t umysql. Error as e:
On_ SQL _error (e)
 
Data = handle_ SQL _result (rs)
Kwargs ["data"] = data
Result = fn (* args, ** kwargs)
Mysqlconn. close ()
Return result
Return wrapper
 
Return decorator
 
 
@ Mysql (SQL = "select * from coolshell ")
Def get_coolshell (data ):
......
.....

Asynchronous thread
Copy codeThe Code is as follows:
From threading import Thread
From functools import wraps
 
Def async (func ):
@ Wraps (func)
Def async_func (* args, ** kwargs ):
Func_hl = Thread (target = func, args = args, kwargs = kwargs)
Func_hl.start ()
Return func_hl
 
Return async_func
 
If _ name _ = '_ main __':
From time import sleep
 
@ Async
Def print_somedata ():
Print 'starting print_somedata'
Sleep (2)
Print 'print _ somedata: 2 sec passed'
Sleep (2)
Print 'print _ somedata: 2 sec passed'
Sleep (2)
Print 'finished print_somedata'
 
Def main ():
Print_somedata ()
Print 'Back in main'
Print_somedata ()
Print 'Back in main'
 
Main ()

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.