python 装饰器

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
云数据库 RDS PostgreSQL,高可用系列 2核4GB
简介:

2015/3/8添加:

注意functools.wraps()函数的作用:调用经过装饰的函数,相当于调用一个新函数,那查看函数参数,注释,甚至函数名的时候,就只能看到装饰器的相关信息,被包装函数的信息被丢掉了。

而wraps则可以帮你转移这些信息,具体参见http://stackoverflow.com/questions/308999/what-does-functools-wraps-do 

测试1

deco运行,但myfunc并没有运行

复制代码
def deco(func):
    print 'before func'
    return func 

def myfunc():
    print 'myfunc() called'
 
myfunc = deco(myfunc)
复制代码

测试2

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

复制代码
def deco(func):
    print 'before func'
    func()
    print 'after func'
    return func 

def myfunc():
    print 'myfunc() called'
 
myfunc = deco(myfunc)
复制代码

测试3

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

复制代码
def deco(func):
    print 'before func'
    func()
    print 'after func'
    return func 

@deco
def myfunc():
    print 'myfunc() called'

myfunc()
复制代码

测试4

这样装饰才行

复制代码
def deco(func):
    def _deco():
        print 'before func'
        func()
        print 'after func'
    return _deco 

@deco
def myfunc():
    print 'myfunc() called'
 
myfunc()
复制代码

测试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()
复制代码

 

 

测试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')
复制代码

测试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')
复制代码

测试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()
复制代码

 

 

测试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()
复制代码

 

实例

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

复制代码
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()
复制代码

 

知识共享许可协议
本文 由 cococo点点 创作,采用 知识共享 署名-非商业性使用-相同方式共享 3.0 中国大陆 许可协议进行许可。欢迎转载,请注明出处:
转载自:cococo点点 http://www.cnblogs.com/coder2012


相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
2天前
|
缓存 测试技术 Python
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
153 99
|
2天前
|
存储 缓存 测试技术
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
137 98
|
7天前
|
缓存 Python
Python中的装饰器:优雅地增强函数功能
Python中的装饰器:优雅地增强函数功能
|
16天前
|
存储 缓存 测试技术
理解Python装饰器:简化代码的强大工具
理解Python装饰器:简化代码的强大工具
|
30天前
|
程序员 测试技术 开发者
Python装饰器:简化代码的强大工具
Python装饰器:简化代码的强大工具
152 92
|
3月前
|
Python
掌握Python装饰器:轻松统计函数执行时间
掌握Python装饰器:轻松统计函数执行时间
260 76
|
22天前
|
设计模式 缓存 运维
Python装饰器实战场景解析:从原理到应用的10个经典案例
Python装饰器是函数式编程的精华,通过10个实战场景,从日志记录、权限验证到插件系统,全面解析其应用。掌握装饰器,让代码更优雅、灵活,提升开发效率。
83 0
|
4月前
|
人工智能 API Python
掌握 Python 文件处理、并行处理和装饰器
本文介绍了 Python 在文件处理、并行处理以及高级功能(如装饰器、Lambda 函数和推导式)的应用。第一部分讲解了文件的基本操作、读写方法及处理大型文件的技巧,并演示了使用 Pandas 处理结构化数据的方式。第二部分探讨了多线程与多进程的并行处理,以及 `concurrent.futures` 模块的简化用法,适合不同类型的任务需求。第三部分则深入装饰器的实现与应用,包括简单装饰器、带参数的装饰器及 `functools.wraps` 的使用,同时简要介绍了 Lambda 函数和推导式的语法与场景。内容实用且全面,帮助读者掌握 Python 高效编程的核心技能。
|
9月前
|
测试技术 数据安全/隐私保护 开发者
探索Python中的装饰器:从基础到高级应用
装饰器在Python中是一个强大且令人兴奋的功能,它允许开发者在不修改原有函数代码的前提下增加额外的功能。本文将通过具体代码示例,带领读者从装饰器的基础概念入手,逐步深入到高级用法,如带参数的装饰器和装饰器嵌套等。无论你是初学者还是有经验的开发者,这篇文章都将为你提供有价值的见解和技巧。
106 6

推荐镜像

更多