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 字符串split的用法分享
Mar 23 Python
python 实现一个贴吧图片爬虫的示例
Oct 12 Python
python实现在pandas.DataFrame添加一行
Apr 04 Python
Python实现的堆排序算法示例
Apr 29 Python
浅谈Python中重载isinstance继承关系的问题
May 04 Python
python中datetime模块中strftime/strptime函数的使用
Jul 03 Python
python版百度语音识别功能
Jul 09 Python
python字典的遍历3种方法详解
Aug 10 Python
Python实现把多维数组展开成DataFrame
Nov 30 Python
python db类用法说明
Jul 07 Python
浅析Python迭代器的高级用法
Jul 16 Python
MoviePy常用剪辑类及Python视频剪辑自动化
Dec 18 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 5.0对象模型深度探索之属性和方法
2008/03/27 PHP
UCenter 批量添加用户的php代码
2012/07/17 PHP
PHP使用strtotime获取上个月、下个月、本月的日期
2015/12/30 PHP
PHP INT类型在内存中占字节详解
2019/07/20 PHP
Jquery数独游戏解析(一)-页面布局
2010/11/05 Javascript
再论Javascript下字符串连接的性能
2011/03/05 Javascript
jQuery控制TR显示隐藏的几种方法
2014/06/18 Javascript
Jquery节点遍历next与nextAll方法使用示例
2014/07/22 Javascript
JS优化与惰性载入函数实例分析
2017/04/06 Javascript
详解axios在node.js中的post使用
2017/04/27 Javascript
Swiper 4.x 使用方法(移动端网站的内容触摸滑动)
2018/05/17 Javascript
vue+element表格导出为Excel文件
2019/09/26 Javascript
jQuery+ajax实现用户登录验证
2020/09/13 jQuery
vue.js封装switch开关组件的操作
2020/10/26 Javascript
Python接收Gmail新邮件并发送到gtalk的方法
2015/03/10 Python
python编程开发之textwrap文本样式处理技巧
2015/11/13 Python
Python的SQLalchemy模块连接与操作MySQL的基础示例
2016/07/11 Python
基于python元祖与字典与集合的粗浅认识
2017/08/23 Python
Python探索之ModelForm代码详解
2017/10/26 Python
python在ubuntu中的几种安装方法(小结)
2017/12/08 Python
对python中的xlsxwriter库简单分析
2018/05/04 Python
python实现公司年会抽奖程序
2019/01/22 Python
使用Python 统计高频字数的方法
2019/01/31 Python
aws 通过boto3 python脚本打pach的实现方法
2020/05/10 Python
Java爬虫技术框架之Heritrix框架详解
2020/07/22 Python
python按照list中字典的某key去重的示例代码
2020/10/13 Python
详解如何在css中引入自定义字体(font-face)
2018/05/17 HTML / CSS
100%有机精油,美容油:House of Pure Essence
2018/10/30 全球购物
某公司C#程序员面试题笔试题
2014/05/26 面试题
英语专业推荐信
2013/11/16 职场文书
2014年关于两会精神的心得体会
2014/03/17 职场文书
大学同学会活动方案
2014/08/20 职场文书
学习优秀共产党员先进事迹思想报告
2014/09/17 职场文书
困难补助申请报告
2015/05/19 职场文书
html中显示特殊符号(附带特殊字符对应表)
2021/06/21 HTML / CSS