This article mainly introduces the Python decorator use examples and practical application examples. This article provides practical use examples such as the Fibonacci series, registration callback functions, mysql encapsulation, and thread asynchronization, for more information, see
Test 1
Deco is running, but myfunc is not running
The 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
The 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
The 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.
The 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
The 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
The 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
The 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
The 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
The 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
The 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
The 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
The 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
The 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 ()