Python装饰器使用示例及实际应用例子

 更新时间:2015年03月06日 09:57:06   投稿:junjie  
这篇文章主要介绍了Python装饰器使用示例及实际应用例子,本文给出了斐波拉契数列、注册回调函数、mysql封装、线程异步等实际使用示例,需要的朋友可以参考下

测试1

deco运行,但myfunc并没有运行

复制代码 代码如下:

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

def myfunc():
    print 'myfunc() called'
 
myfunc = deco(myfunc)

测试2

需要的deco中调用myfunc,这样才可以执行

复制代码 代码如下:

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

def myfunc():
    print 'myfunc() called'
 
myfunc = deco(myfunc)

测试3

@函数名 但是它执行了两次

复制代码 代码如下:

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

@deco
def myfunc():
    print 'myfunc() called'

myfunc()

测试4

这样装饰才行

复制代码 代码如下:

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

@deco
def myfunc():
    print 'myfunc() called'
 
myfunc()

测试5

@带参数,使用嵌套的方法

复制代码 代码如下:

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()

测试6

函数参数传递

复制代码 代码如下:

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')

测试7

未知参数个数

复制代码 代码如下:

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')

测试8

class作为修饰器

复制代码 代码如下:

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()

测试9

复制代码 代码如下:

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()

实例

给函数做缓存 --- 斐波拉契数列

复制代码 代码如下:

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)

注册回调函数 --- web请求回调

复制代码 代码如下:

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封装 -- 很好用

复制代码 代码如下:

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):
    ... ...
    ... ..

线程异步

复制代码 代码如下:

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()

相关文章

  • 基于Django URL传参 FORM表单传数据 get post的用法实例

    基于Django URL传参 FORM表单传数据 get post的用法实例

    今天小编就为大家分享一篇基于Django URL传参 FORM表单传数据 get post的用法实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-05-05
  • Python如何求取逆序数

    Python如何求取逆序数

    这篇文章主要介绍了Python如何求取逆序数问题,具有很好的参考价值,希望大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12
  • python使用cookielib库示例分享

    python使用cookielib库示例分享

    Python中cookielib库(python3中为http.cookiejar)为存储和管理cookie提供客户端支持,下面是使用示例
    2014-03-03
  • Python 使用threading+Queue实现线程池示例

    Python 使用threading+Queue实现线程池示例

    今天小编就为大家分享一篇Python 使用threading+Queue实现线程池示例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-12-12
  • Python面向对象程序设计之私有变量,私有方法原理与用法分析

    Python面向对象程序设计之私有变量,私有方法原理与用法分析

    这篇文章主要介绍了Python面向对象程序设计之私有变量,私有方法,结合实例形式分析了Python面向对象程序设计中私有变量,私有方法相关概念、原理、用法及操作注意事项,需要的朋友可以参考下
    2020-03-03
  • python批量处理文件或文件夹

    python批量处理文件或文件夹

    这篇文章主要为大家详细介绍了python批量处理文件或文件夹,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-08-08
  • Pycharm学习教程(4) Python解释器的相关配置

    Pycharm学习教程(4) Python解释器的相关配置

    这篇文章主要为大家详细介绍了最全的Pycharm学习教程第四篇,Python解释器配置,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-05-05
  • tensorflow pb to tflite 精度下降详解

    tensorflow pb to tflite 精度下降详解

    这篇文章主要介绍了tensorflow pb to tflite 精度下降详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-05-05
  • Python使用pyinstaller实现学生管理系统流程

    Python使用pyinstaller实现学生管理系统流程

    pyinstaller是一个非常简单的打包python的py文件的库,下面这篇文章主要给大家介绍了关于Python Pyinstaller库安装步骤以及使用方法的相关资料,文中通过图文介绍的非常详细,需要的朋友可以参考下
    2023-02-02
  • Python之os操作方法(详解)

    Python之os操作方法(详解)

    下面小编就为大家带来一篇Python之os操作方法(详解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06

最新评论