python 装饰器

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介:

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


相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
14天前
|
监控 Python
Python中的装饰器:提升代码灵活性与可读性
在Python编程中,装饰器是一种强大的工具,能够提升代码的灵活性和可读性。本文将介绍装饰器的基本概念、使用方法以及实际应用场景,帮助读者更好地理解和利用这一功能。
|
17天前
|
缓存 监控 Python
解密Python中的装饰器:优雅而强大的编程利器
Python中的装饰器是一种强大而又优雅的编程工具,它能够在不改变原有代码结构的情况下,为函数或类添加新的功能和行为。本文将深入解析Python装饰器的原理、用法和实际应用,帮助读者更好地理解和利用这一技术,提升代码的可维护性和可扩展性。
|
1月前
|
缓存 算法 测试技术
Python中的装饰器:原理与实践
【2月更文挑战第29天】 在Python编程领域,装饰器是一种强大的工具,它允许我们在不修改原始函数代码的情况下,增加或修改函数的行为。本文将深入探讨Python装饰器的概念、实现原理以及实际应用,帮助读者掌握这一技术并在实际项目中灵活运用。
|
1天前
|
存储 缓存 Python
Python装饰器
Python装饰器
4 0
|
1天前
|
数据安全/隐私保护 Python
Python中的装饰器:提升代码可读性和灵活性
Python中的装饰器是一种强大的编程工具,能够提升代码的可读性和灵活性。本文将深入探讨装饰器的原理和用法,以及如何利用装饰器来简化代码、实现日志记录、权限控制等功能,从而让你的Python代码更加优雅和高效。
|
7天前
|
数据安全/隐私保护 Python
Python中的装饰器:提升代码可读性与灵活性
Python中的装饰器是一种强大的工具,可以在不改变函数原有逻辑的情况下,为函数添加额外的功能。本文将介绍装饰器的基本概念和用法,并通过实例演示如何利用装饰器提升代码的可读性和灵活性,使代码更加简洁、易于维护。
|
7天前
|
缓存 大数据 数据处理
Python迭代器、生成器和装饰器探究
【4月更文挑战第2天】 迭代器是遍历集合元素的对象,实现`__iter__()`和`__next__()`方法。示例中自定义迭代器`MyIterator`用于生成整数序列。 - 生成器简化了迭代器实现,利用`yield`关键词实现状态保存,减少内存占用。示例中的`my_generator`函数即为一个生成器。 - 装饰器用于修改函数行为,如日志记录、性能分析。装饰器`my_decorator`在函数调用前后添加额外代码。
23 0
|
9天前
|
程序员 Python
Python中的装饰器:提升代码可读性与灵活性
在Python编程中,装饰器是一种强大的工具,可以在不修改原始代码的情况下,动态地添加功能。本文将深入探讨Python中装饰器的原理、用法和实际应用,以及如何利用装饰器提升代码的可读性和灵活性。
|
11天前
|
缓存 开发者 Python
深入探讨Python中的装饰器:提升代码可读性与灵活性
在Python编程中,装饰器是一种强大的工具,可以在不修改原始函数代码的情况下,对其行为进行扩展或修改。本文将深入探讨装饰器的原理和用法,以及如何利用装饰器提升代码的可读性和灵活性,为Python开发者提供更加优雅和高效的编程方式。
|
12天前
|
测试技术 开发者 Python
Python中的装饰器:优雅而强大的函数修饰工具
在Python编程中,装饰器是一种强大的工具,用于修改函数或方法的行为。本文将深入探讨Python中装饰器的概念、用法和实际应用,以及如何利用装饰器实现代码的优雅和高效。