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入门教程之if语句的用法
May 14 Python
详解Python字符串对象的实现
Dec 24 Python
对numpy中array和asarray的区别详解
Apr 17 Python
python获取当前目录路径和上级路径的实例
Apr 26 Python
使用python将图片格式转换为ico格式的示例
Oct 22 Python
用python求一个数组的和与平均值的实现方法
Jun 29 Python
python opencv将图片转为灰度图的方法示例
Jul 31 Python
django 解决自定义序列化返回处理数据为null的问题
May 20 Python
python中如何进行连乘计算
May 28 Python
Python之字典添加元素的几种方法
Sep 30 Python
在Python中字典按值排序的实现方法
Nov 12 Python
python解包概念及实例
Feb 17 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
ie6 动态缩略图不显示的原因
2009/06/21 PHP
PHP 图片上传实现代码 带详细注释
2010/04/29 PHP
解析web文件操作常见安全漏洞(目录、文件名检测漏洞)
2013/06/29 PHP
PHPExcel笔记, mpdf导出
2016/05/03 PHP
phpcms实现验证码替换及phpcms实现全站搜索功能教程详解
2017/12/13 PHP
用正则表达式 动态创建/增加css style script 兼容IE firefox
2009/03/10 Javascript
Javascript 类与静态类的实现(续)
2010/04/02 Javascript
让人印象深刻的10个jQuery手风琴效果应用
2012/05/08 Javascript
Web跨浏览器进程通信(Web跨域)
2013/04/17 Javascript
多次注册事件会导致一个事件被触发多次的解决方法
2013/08/12 Javascript
jQuery的css()方法用法实例
2014/12/24 Javascript
Jquery easyui开启行编辑模式增删改操作
2016/01/14 Javascript
AngularJs页面筛选标签小功能
2016/08/01 Javascript
JavaScript面试开发常用的知识点总结
2016/08/08 Javascript
jQuery通过ajax方法获取json数据不执行success的原因及解决方法
2016/10/15 Javascript
详解获取jq ul第一个li定位的四种解决方案
2016/11/23 Javascript
JavaScript中的高级函数
2018/01/04 Javascript
JavaScript求一组数的最小公倍数和最大公约数常用算法详解【面向对象,回归迭代和循环】
2018/05/07 Javascript
vue elementUI table 自定义表头和行合并的实例代码
2019/05/22 Javascript
vue使用require.context实现动态注册路由
2020/12/25 Vue.js
[02:43]DOTA2亚洲邀请赛场馆攻略——带你走进东方体育中心
2018/03/19 DOTA
Python 爬虫模拟登陆知乎
2016/09/23 Python
django站点管理详解
2017/12/12 Python
python中文乱码不着急,先看懂字节和字符
2017/12/20 Python
Python利用递归实现文件的复制方法
2018/10/27 Python
python矩阵运算,转置,逆运算,共轭矩阵实例
2020/05/11 Python
PyQt5中QSpinBox计数器的实现
2021/01/18 Python
Python爬虫入门教程01之爬取豆瓣Top电影
2021/01/24 Python
新西兰便宜隐形眼镜购买网站:QUICKLENS New Zealand
2019/03/02 全球购物
Monica Vinader官网:英国轻奢珠宝品牌
2020/02/05 全球购物
印度电子产品购物网站:Vijay Sales
2021/02/16 全球购物
新员工培训个人的自我评价
2013/10/09 职场文书
入党思想汇报怎么写
2014/04/03 职场文书
暑假社会实践心得体会
2014/09/02 职场文书
法人代表身份证明书及授权委托书
2014/09/16 职场文书
美元符号 $
2022/02/17 杂记