Python装饰器使用示例及实际应用例子_python

测试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()

时间: 2024-09-01 13:21:52

Python装饰器使用示例及实际应用例子_python的相关文章

python 装饰器功能以及函数参数使用介绍_python

简单的说:装饰器主要作用就是对函数进行一些修饰,它的出现是在引入类方法和静态方法的时候为了定义静态方法出现的.例如为了把foo()函数声明成一个静态函数 复制代码 代码如下: class Myclass(object): def staticfoo(): ............ ............ staticfoo = staticmethod(staticfoo) 可以用装饰器的方法实现: 复制代码 代码如下: class Myclass(object): @staticmethod

巧用Python装饰器 免去调用父类构造函数的麻烦_python

先看一段代码: 复制代码 代码如下: class T1(threading.Thread): def __init__(self, a, b, c): super(T1, self).__init__() self.a = a self.b = b self.c = c def run(self): print self.a, self.b, self.c 代码定义了一个继承自threading.Thread的class,看这句 super(T1, self).__init__() 也有些人喜欢

九步学会Python装饰器

  本文实例讲述了Python装饰器.分享给大家供大家参考.具体分析如下: 这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方式. 第一步:最简单的函数,准备附加额外功能 ? 1 2 3 4 5 6 # -*- coding:gbk -*- '''示例1: 最简单的函数,表示调用了两次''' def myfunc(): print("myfunc() called.") myfunc() myfunc() 第二步:使用装饰函数在函数执行前和执行后分别附加额外功能 ?

详解Python装饰器由浅入深_python

装饰器的功能在很多语言中都有,名字也不尽相同,其实它体现的是一种设计模式,强调的是开放封闭原则,更多的用于后期功能升级而不是编写新的代码.装饰器不光能装饰函数,也能装饰其他的对象,比如类,但通常,我们以装饰函数为例子介绍其用法.要理解在Python中装饰器的原理,需要一步一步来.本文尽量描述得浅显易懂,从最基础的内容讲起. (注:以下使用Python3.5.1环境) 一.Python的函数相关基础 第一,必须强调的是python是从上往下顺序执行的,而且碰到函数的定义代码块是不会立即执行它的,只

对Python 装饰器的理解心得

最近写一个py脚本来整理电脑中的文档,其中需要检校输入的字符,为了不使代码冗长,想到使用装 饰器. 上网搜索有关python的装饰器学习文档,主要看的是AstralWind的一篇博文,以及Limodou的一篇文章 .作为初学者,这两篇文章对新手有很大的帮助,但仍然有些不易理解的地方.因此在此以一个初学者的 认知记录一下python的装饰器的学习心得. 1. 什么是装饰器? 顾名思义,装饰器就是在方法上方标一个带有@符号的方法名,以此来对被装饰的方法进行点缀改造. 当你明白什么是装饰器之后,自然会

Python装饰器详解

装饰器(decorator)是一种高级Python语法.装饰器可以对一个函数.方法或者类进行加工.在Python中,我们有多种方法对函数和类进行加工,比如在Python闭包中,我们见到函数对象作为某一个函数的返回结果.相对于其它方式,装饰器语法简单,代码可读性高.因此,装饰器在Python项目中有广泛的应用. 装饰器最早在Python 2.5中出现,它最初被用于加工函数和方法这样的可调用对象(callable object,这样的对象定义有__call__方法).在Python 2.6以及之后的

Python装饰器使用实例:验证参数合法性

          这篇文章主要介绍了Python装饰器使用实例:验证参数合法性,本文直接给出代码实例,代码中包含详细注释,需要的朋友可以参考下               python是不带静态检查的动态语言,有时候需要在调用函数时保证参数合法.检查参数合法性是一个显著的切面场景,各个函数都可能有这个需求.但另一方面,参数合法性是不是应该由调用方来保证比较好也是一个需要结合实际才能回答的问题,总之双方约定好,不要都不检查或者都检查就可以了.下面这个模块用于在函数上使用装饰器进行参数的合法性验证

对于Python装饰器使用的一些建议

  这篇文章主要介绍了对于Python装饰器使用的一些建议,装饰器是Python学习进阶中的重要知识,需要的朋友可以参考下 装饰器基本概念 大家都知道装饰器是一个很著名的设计模式,经常被用于 AOP (面向切面编程)的场景,较为经典的有插入日志,性能测试,事务处理,Web权限校验, Cache等. Python 语言本身提供了装饰器语法(@),典型的装饰器实现如下: ? 1 2 3 @function_wrapper def function(): pass @实际上是 python2.4 才提

对Python装饰器的个人理解方法

0.说明                   在自己好好总结并对Python装饰器的执行过程进行分解之前,对于装饰器虽然理解它的基本工作方式,但对于存在复杂参数的装饰器(装饰器和函数本身都有参数),总是会感到很模糊,即使这会弄懂了,下一次也很快忘记,其实本质上还是没有多花时间去搞懂其中的细节问题.         虽然网络上已经有很多这样的文章,但显然都是别人的思想,因此自己总是记不牢,所以花点时间自己好好整理一下.         最近在对<Python核心编程>做总结,收获了不少,下面分享