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中的tkinter模块作图的方法
Feb 07 Python
详解Python自建logging模块
Jan 29 Python
python中使用iterrows()对dataframe进行遍历的实例
Jun 09 Python
Anaconda 离线安装 python 包的操作方法
Jun 11 Python
Python for循环中的陷阱详解
Jul 13 Python
利用pandas读取中文数据集的方法
Jul 25 Python
对Python 3.2 迭代器的next函数实例讲解
Oct 18 Python
利用python-docx模块写批量生日邀请函
Aug 26 Python
基于pytorch的lstm参数使用详解
Jan 14 Python
pandas数据分组groupby()和统计函数agg()的使用
Mar 04 Python
只需要100行Python代码就可以实现的贪吃蛇小游戏
May 27 Python
Python实现双向链表基本操作
May 25 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 多关键字 高亮显示实现代码
2012/04/23 PHP
浅谈php函数serialize()与unserialize()的使用方法
2014/08/19 PHP
php cli配置文件问题分析
2015/10/15 PHP
php利用云片网实现短信验证码功能的示例代码
2017/11/18 PHP
JS 文字符串转换unicode编码函数
2009/05/30 Javascript
解析DHTML,JavaScript,DOM,BOM以及WEB标准的描述
2013/06/19 Javascript
jquery验证表单中的单选与多选实例
2013/08/18 Javascript
JS倒计时代码汇总
2014/11/25 Javascript
JavaScript对象之深度克隆介绍
2014/12/08 Javascript
使用纯javascript实现放大镜效果
2015/03/18 Javascript
浅析javascript中的事件代理
2015/11/06 Javascript
Javascript removeChild()删除节点及删除子节点的方法
2015/12/27 Javascript
必备的JS调试技巧汇总
2016/07/20 Javascript
javascript输出AscII码扩展集中的字符方法
2016/12/26 Javascript
20170918 前端开发周报之JS前端开发必看
2017/09/18 Javascript
JavaScript实现二叉树的先序、中序及后序遍历方法详解
2017/10/26 Javascript
详解组件库的webpack构建速度优化
2018/06/18 Javascript
vue中引用swiper轮播插件的教程详解
2018/08/16 Javascript
利用Webpack实现小程序多项目管理的方法
2019/02/25 Javascript
微信小程序连续签到7天积分获得功能的示例代码
2020/08/20 Javascript
通过源码分析Python中的切片赋值
2017/05/08 Python
人机交互程序 python实现人机对话
2017/11/14 Python
python中的闭包函数
2018/02/09 Python
python 图像平移和旋转的实例
2019/01/10 Python
python super的使用方法及实例详解
2019/09/25 Python
python使用多线程查询数据库的实现示例
2020/08/17 Python
Python尾递归优化实现代码及原理详解
2020/10/09 Python
selenium判断元素是否存在的两种方法小结
2020/12/07 Python
AmazeUI 图标的示例代码
2020/08/13 HTML / CSS
民事辩护词范文
2015/05/21 职场文书
讲座开场白台词和结束语
2015/05/29 职场文书
2016十一国庆节慰问信
2015/12/01 职场文书
2016年大学生实习单位评语
2015/12/01 职场文书
详解Python自动化之文件自动化处理
2021/06/21 Python
mongodb数据库迁移变更的解决方案
2021/09/04 MongoDB
关于MybatisPlus配置双数据库驱动连接数据库问题
2022/01/22 Java/Android