Python Decorator usage examples and practical application examples

Source: Internet
Author: User
Tags python decorator
Test 1

Deco runs, but MyFunc does not run

Copy the Code code as follows:


def deco (func):
print ' before Func '
return func

Def myfunc ():
print ' MyFunc () called '

MyFunc = Deco (MyFunc)

Test 2

Need to call MyFunc in Deco in order to execute
Copy the Code code 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 executes twice.

Copy the Code code as follows:


def deco (func):
print ' before Func '
Func ()
print ' after Func '
return func

@deco
Def myfunc ():
print ' MyFunc () called '

MyFunc ()

Test 4

It's a decoration.

Copy the Code code 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

@ with parameters, using nested methods
Copy the Code code as follows:


def deco (ARG):
def _deco (func):
Print arg
Def __deco ():
print ' before Func '
Func ()
print ' after Func '
Return __deco
Return _deco

@deco (' deco ')
Def myfunc ():
print ' MyFunc () called '

MyFunc ()

Test 6

function parameter passing
Copy the Code code 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 (' deco ')
def myfunc (str):
print ' MyFunc () called ', str

MyFunc (' Hello ')

Test 7

Unknown number of parameters
Copy the Code code 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 (' Deco1 ')
def myfunc1 (str):
print ' myfunc1 () called ', str

@deco (' Deco2 ')
def myfunc2 (STR1,STR2):
print ' Myfunc2 () called ', str1, str2

Myfunc1 (' Hello ')

MYFUNC2 (' Hello ', ' world ')

Test 8

Class as Decorator
Copy the Code code 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 the Code code 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

To cache a function---Fibonacci sequence

Copy the Code code 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)

Registering a callback function---Web request callback

Copy the Code code 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 Package--Very useful
Copy the Code code as follows:


Import Umysql
From Functools Import Wraps

Class Configuraion:
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 = Configuraion (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, {})
Except 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):
... ...
... ..

Thread Async
Copy the Code code 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.