python 装饰器应用
1 注册回调函数
下面这个示例展示了通过URL的路由来调用相关注册的函数示例:
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')
注意:
1)上面这个示例中,用类的实例来做decorator。
2)decorator类中没有__call__(),但是wrapper返回了原函数。所以,原函数没有发生任何变化。
2 打印日志
from functools import wraps
import inspect
def get_line_number():
return inspect.currentframe().f_back.f_back.f_lineno
def logger(loglevel):
def log_decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
ts = time.time()
result = fn(*args, **kwargs)
te = time.time()
print "function = " + fn.__name__,
print " arguments = {0} {1}".format(args, kwargs)
#print " return = {0}".format(result)
print " time = %.6f sec" % (te-ts)
if (loglevel == 'debug'):
print " called_from_line : " + str(get_line_number())
return result
return wrapper
return log_decoratorspam(1,2,3)
3 调用追踪
import sys,os,linecache
def trace(f):
def globaltrace(frame, why, arg):
if why == "call": return localtrace
return None
def localtrace(frame=1, why=2, arg=4):
if why == "line":
# record the file name and line number of every trace
filename = frame.f_code.co_filename
lineno = frame.f_lineno
bname = os.path.basename(filename)
print "{}({}): {}".format( bname,
lineno,
linecache.getline(filename, lineno)),
return localtrace
def _f(*args, **kwds):
sys.settrace(globaltrace)
result = f(*args, **kwds)
sys.settrace(None)
return result
return _f
@trace
def xxx():
a=1
print a
xxx() #调用
4 单例模式
# coding=utf-8
# 测试utf-8编码
# 单例装饰器
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# 使用装饰器实现简单的单例模式
def singleton(cls):
instances = dict() # 初始为空
def _singleton(*args, **kwargs):
if cls not in instances: #如果不存在, 则创建并放入字典
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return _singleton
@singleton
class Test(object):
pass
if __name__ == '__main__':
t1 = Test()
t2 = Test()
# 两者具有相同的地址
print t1
print t2
python 装饰器应用的更多相关文章
- 关于python装饰器
关于python装饰器,不是系统的介绍,只是说一下某些问题 1 首先了解变量作用于非常重要 2 其次要了解闭包 def logger(func): def inner(*args, **kwargs) ...
- python装饰器通俗易懂的解释!
1.python装饰器 刚刚接触python的装饰器,简直懵逼了,直接不懂什么意思啊有木有,自己都忘了走了多少遍Debug,查了多少遍资料,猜有点点开始明白了.总结了一下解释得比较好的,通俗易懂的来说 ...
- Python 装饰器学习
Python装饰器学习(九步入门) 这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方式. 第一步:最简单的函数,准备附加额外功能 1 2 3 4 5 6 7 8 # -*- c ...
- python 装饰器修改调整函数参数
简单记录一下利用python装饰器来调整函数的方法.现在有个需求:参数line范围为1-16,要求把9-16的范围转化为1-8,即9对应1,10对应2,...,16对应8. 下面是例子: def fo ...
- python 装饰器学习(decorator)
最近看到有个装饰器的例子,没看懂, #!/usr/bin/python class decorator(object): def __init__(self,f): print "initi ...
- Python装饰器详解
python中的装饰器是一个用得非常多的东西,我们可以把一些特定的方法.通用的方法写成一个个装饰器,这就为调用这些方法提供一个非常大的便利,如此提高我们代码的可读性以及简洁性,以及可扩展性. 在学习p ...
- 关于python装饰器(Decorators)最底层理解的一句话
一个decorator只是一个带有一个函数作为参数并返回一个替换函数的闭包. http://www.xxx.com/html/2016/pythonhexinbiancheng_0718/1044.h ...
- Python装饰器由浅入深
装饰器的功能在很多语言中都有,名字也不尽相同,其实它体现的是一种设计模式,强调的是开放封闭原则,更多的用于后期功能升级而不是编写新的代码.装饰器不光能装饰函数,也能装饰其他的对象,比如类,但通常,我们 ...
- Python装饰器与面向切面编程
今天来讨论一下装饰器.装饰器是一个很著名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志.性能测试.事务处理等.装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量函数中与函数 ...
- python装饰器方法
前几天向几位新同事介绍项目,被问起了@login_required的实现,我说这是django框架提供的装饰器方法,验证用户是否登录,只要这样用就行了,因为自己不熟,并没有做过多解释. 今天查看dja ...
随机推荐
- vue引入警告:There are multiple modules with names that only differ in casing. This can lead to unexpected behavior when compiling on a filesystem with other case-semantic. Use equal casing. Compare these
在写vue项目的时候 当我使用 : import dataSource from '../overseaProduct/house/dataSource'; 引入dataSource文件的时候:控制台 ...
- JFinal(2)JFinal 学习资料
JFinal 学习资料 :http://pan.baidu.com/s/1hsOcQ0G 密码:7lq3 , jfinal社区收费会员内部部分资料,博主网络搜集而来
- bash shell的ANSI控制
格式: echo -e "\033[字背景颜色;字体颜色m字符串\033[0m" 例如: echo -e "\033[41;36m something here \03 ...
- [Vue warn]: Duplicate keys detected: '0'. This may cause an update error.
1.[Vue warn]: Duplicate keys detected: '0'. This may cause an update error. 第一眼看到这个错误一脸懵逼,项目使用很久了,代码 ...
- 13 Windows编程——系统内置窗口子类型之静态子窗口
静态子窗口类型 wndclass:static 源码 #include<Windows.h> #include<Windowsx.h> HINSTANCE G_h; LRESU ...
- 能用的单纯形法python代码
网上找了一些代码,发现有一些是不能用的,出现错误说集合为空 1.网上出现了好多次,但是不能用的,只能部分模型能用,比如例子中所示 原链接:https://www.jianshu.com/p/b233c ...
- [唐胡璐]Selenium技巧- Prop.Properties配置测试应用的环境和其他配置项
prop.propertiesfile contains important info that needs to be changed before the test is run, such a ...
- DevExpress Winforms使用大揭秘!那些你不了解的SvgImageBox控件
DevExpress Winforms Controls 内置140多个UI控件和库,完美构建流畅.美观且易于使用的应用程序.无论是Office风格的界面,还是分析处理大批量的业务数据,DevExpr ...
- Vue-main.js中的一些配置
import Vue from 'vue' import App from './App.vue' import router from './router' import store from '. ...
- UEditor设置内容setContent()失效的解决方法
ueditor常见用法: https://blog.csdn.net/qq_31879707/article/details/54894735#UE.Editor:setContent() UEdit ...