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嵌套字典比较值与取值的实现示例
Nov 03 Python
使用python生成目录树
Mar 29 Python
Python获取系统所有进程PID及进程名称的方法示例
May 24 Python
pygame游戏之旅 添加游戏暂停功能
Nov 21 Python
pytorch 调整某一维度数据顺序的方法
Dec 08 Python
Python代码打开本地.mp4格式文件的方法
Jan 03 Python
python实现微信定时每天和女友发送消息
Apr 29 Python
python使用writerows写csv文件产生多余空行的处理方法
Aug 01 Python
pytorch 加载(.pth)格式的模型实例
Aug 20 Python
python随机生成大小写字母数字混合密码(仅20行代码)
Feb 01 Python
Tensorflow:转置函数 transpose的使用详解
Feb 11 Python
python实现井字棋小游戏
Mar 04 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版(2)
2006/10/09 PHP
判断Keep-Alive模式的HTTP请求的结束的实现代码
2011/08/06 PHP
基于PHP生成简单的验证码
2016/06/01 PHP
PHP实现对二维数组某个键排序的方法
2016/09/14 PHP
jQuery each()小议
2010/03/18 Javascript
关于可运行代码无法正常执行的使用说明
2010/05/13 Javascript
JavaScript 产生不重复的随机数三种实现思路
2012/12/13 Javascript
关于js注册事件的常用方法
2013/04/03 Javascript
Js中setTimeout()和setInterval() 何时被调用执行的用法
2013/04/12 Javascript
jQuery 插件开发指南
2014/11/14 Javascript
PHPMyAdmin导入时提示文件大小超出PHP限制的解决方法
2015/03/30 Javascript
JavaScript数据结构与算法之栈与队列
2016/01/29 Javascript
浅谈jQuery的bind和unbind事件(绑定和解绑事件)
2017/03/02 Javascript
vue的过滤器filter实例详解
2018/09/17 Javascript
jQuery实现弹出层效果
2019/12/10 jQuery
实例讲解Python编程中@property装饰器的用法
2016/06/20 Python
Python+pandas计算数据相关系数的实例
2018/07/03 Python
Python找出微信上删除你好友的人脚本写法
2018/11/01 Python
Django和Flask框架优缺点对比
2019/10/24 Python
Python enumerate函数遍历数据对象组合过程解析
2019/12/11 Python
Python实现Word表格转成Excel表格的示例代码
2020/04/16 Python
使用Keras实现Tensor的相乘和相加代码
2020/06/18 Python
Python中的With语句的使用及原理
2020/07/29 Python
附答案的Java面试题
2012/11/19 面试题
软件工程师面试题
2012/06/25 面试题
DTD的含义以及作用
2014/01/26 面试题
入党转预备思想汇报
2014/01/07 职场文书
宿舍打麻将检讨书
2014/01/24 职场文书
机械制造毕业生求职信
2014/03/03 职场文书
淘宝客服专员岗位职责
2014/04/11 职场文书
晋江市委常委班子四风问题整改工作方案
2014/10/26 职场文书
后备干部推荐材料
2014/12/24 职场文书
2015年度合同管理工作总结
2015/05/22 职场文书
2015年会计年终工作总结
2015/05/26 职场文书
使用qt quick-ListView仿微信好友列表和聊天列表的示例代码
2021/06/13 Python
Python matplotlib可视化之绘制韦恩图
2022/02/24 Python