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


Posted in Python onMarch 06, 2015

测试1

deco运行,但myfunc并没有运行

def deco(func):

    print 'before func'

    return func
def myfunc():

    print 'myfunc() called'

 

myfunc = deco(myfunc)

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

测试2

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

def deco(func):

    print 'before func'

    func()

    print 'after func'

    return func
def myfunc():

    print 'myfunc() called'

 

myfunc = deco(myfunc)

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

测试3

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

def deco(func):

    print 'before func'

    func()

    print 'after func'

    return func
@deco

def myfunc():

    print 'myfunc() called'
myfunc()

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

测试4

这样装饰才行

def deco(func):

    def _deco():

        print 'before func'

        func()

        print 'after func'

    return _deco
@deco

def myfunc():

    print 'myfunc() called'

 

myfunc()

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

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

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

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

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

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

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

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

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

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

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

实例

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

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()
Python 相关文章推荐
跟老齐学Python之开始真正编程
Sep 12 Python
python实现超简单端口转发的方法
Mar 13 Python
python基于右递归解决八皇后问题的方法
May 25 Python
Python中序列的修改、散列与切片详解
Aug 27 Python
TensorFlow平台下Python实现神经网络
Mar 10 Python
对python使用http、https代理的实例讲解
May 07 Python
python opencv旋转图像(保持图像不被裁减)
Jul 26 Python
Python字典的核心底层原理讲解
Jan 24 Python
Python 日期区间处理 (本周本月上周上月...)
Aug 08 Python
Python ADF 单位根检验 如何查看结果的实现
Jun 03 Python
如何使用 Flask 做一个评论系统
Nov 27 Python
python中Mako库实例用法
Dec 31 Python
Python迭代器和生成器介绍
Mar 06 #Python
Python __setattr__、 __getattr__、 __delattr__、__call__用法示例
Mar 06 #Python
Python比较文件夹比另一同名文件夹多出的文件并复制出来的方法
Mar 05 #Python
Python挑选文件夹里宽大于300图片的方法
Mar 05 #Python
python基于windows平台锁定键盘输入的方法
Mar 05 #Python
Python格式化压缩后的JS文件的方法
Mar 05 #Python
Python随机生成彩票号码的方法
Mar 05 #Python
You might like
如何使用PHP获取网络上文件
2006/10/09 PHP
php实现的一段简单概率相关代码
2016/05/30 PHP
php抽象类和接口知识点整理总结
2019/08/02 PHP
PHP 代码简洁之道(小结)
2019/10/16 PHP
让您的菜单不离网站
2006/10/03 Javascript
javascript:void(0)使用探讨
2013/08/27 Javascript
javascript:void(0)的问题使用探讨
2014/04/10 Javascript
JavaScript实现下拉菜单的显示和隐藏
2016/01/05 Javascript
IE下JS保存图片的简单实例
2016/07/15 Javascript
AngularJS基础 ng-disabled 指令详解及简单示例
2016/08/01 Javascript
jQuery图片前后对比插件beforeAfter用法示例【附demo源码下载】
2016/09/20 Javascript
探索Vue.js component内容实现
2016/11/03 Javascript
Python内置函数bin() oct()等实现进制转换
2012/12/30 Python
本地文件上传到七牛云服务器示例(七牛云存储)
2014/01/11 Python
python WindowsError的错误代码详解
2017/07/23 Python
Tensorflow之Saver的用法详解
2018/04/23 Python
Python实现的简单线性回归算法实例分析
2018/12/26 Python
对Python3使运行暂停的方法详解
2019/02/18 Python
python批量创建指定名称的文件夹
2019/03/21 Python
python3 打印输出字典中特定的某个key的方法示例
2019/07/06 Python
python tkinter 设置窗口大小不可缩放实例
2020/03/04 Python
matplotlib教程——强大的python作图工具库
2020/10/15 Python
汽车维修与检测专业应届生求职信
2013/11/12 职场文书
电厂厂长岗位职责
2014/01/02 职场文书
家长学校实施方案
2014/03/15 职场文书
老公爱的承诺书
2014/03/31 职场文书
三八妇女节活动总结
2014/05/04 职场文书
手术室护士节演讲稿
2014/08/27 职场文书
学校感恩节活动策划方案
2014/10/06 职场文书
学习十八届四中全会精神思想汇报
2014/10/23 职场文书
2014年乡镇人大工作总结
2014/11/25 职场文书
2014年政协委员工作总结
2014/12/01 职场文书
2015清明节祭奠英烈寄语大全
2015/03/04 职场文书
保险内勤岗位职责
2015/04/13 职场文书
公司开业致辞
2015/07/29 职场文书
2019财务转正述职报告
2019/06/27 职场文书