- 浏览: 241928 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (127)
- vim (3)
- python (44)
- pymysql (1)
- mysql (9)
- macvim (1)
- erlang (3)
- twisted (0)
- tornado (5)
- django (7)
- postgresql (5)
- sql (1)
- java (7)
- tech (4)
- cache (1)
- lifestyle (3)
- html (1)
- ubuntu (2)
- rabbitmq (1)
- algorithm (8)
- Linux (4)
- Pythonista (1)
- thread (1)
- sort (6)
- 设计模式 (1)
- search (1)
- Unix (6)
- Socket (3)
- C (2)
- web (1)
- gc (1)
- php (10)
- macos (1)
最新评论
-
2057:
这个程序有bug。
查找算法学习之二分查找(Python版本)——BinarySearch -
dotjar:
NB
一个Python程序员的进化[转]
Contains:
首先我们看下tornado中使用的装饰器
1、@tornado.web.authenticated
接下来代码需要验证用户登陆的方法都可以使用这个装饰器,通过使用这个装饰器可以简化很多重复验证的代码,只需要在方法上面加上@tornado.web.authenticated就ok了。
2、@tornado.web.asynchronous
这个装饰器的会把self._auto_finish 置为 False。
接下来,我们写个单利模式的装饰器:
result is :
<__main__.Foo instance at 0x103152c20> <__main__.Foo instance at 0x103152c20> True
<__main__.Bar instance at 0x103152c68> <__main__.Bar instance at 0x103152cb0> False
@singleton这个装饰器实现了类的单例模式,可以确保类只会被实例化一次。
使用装饰器对参数以及方法返回结果的验证方法:
result:
assert a > 100000,"arg %r must gt 100000" % a
AssertionError: arg 5000 must gt 100000
参考资料:
http://www.python.org/dev/peps/pep-0318/
http://wiki.python.org/moin/PythonDecorators
http://wiki.python.org/moin/PythonDecoratorLibrary
http://blog.csdn.net/beckel/article/details/3585352
http://blog.csdn.net/beckel/article/details/3945147
http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html
http://mrcoles.com/blog/3-decorator-examples-and-awesome-python/
http://stackoverflow.com/questions/308999/what-does-functools-wraps-do
- 1、decorators
- 2、functools
首先我们看下tornado中使用的装饰器
1、@tornado.web.authenticated
引用
Decorate methods with this to require that the user be logged in.
def authenticated(method): """Decorate methods with this to require that the user be logged in.""" @functools.wraps(method) def wrapper(self, *args, **kwargs): if not self.current_user: if self.request.method in ("GET", "HEAD"): url = self.get_login_url() if "?" not in url: if urlparse.urlsplit(url).scheme: # if login url is absolute, make next absolute too next_url = self.request.full_url() else: next_url = self.request.uri url += "?" + urllib.urlencode(dict(next=next_url)) self.redirect(url) return raise HTTPError(403) return method(self, *args, **kwargs) return wrapper
接下来代码需要验证用户登陆的方法都可以使用这个装饰器,通过使用这个装饰器可以简化很多重复验证的代码,只需要在方法上面加上@tornado.web.authenticated就ok了。
2、@tornado.web.asynchronous
def asynchronous(method): @functools.wraps(method) def wrapper(self, *args, **kwargs): if self.application._wsgi: raise Exception("@asynchronous is not supported for WSGI apps") self._auto_finish = False with stack_context.ExceptionStackContext( self._stack_context_handle_exception): return method(self, *args, **kwargs) return wrapper
这个装饰器的会把self._auto_finish 置为 False。
接下来,我们写个单利模式的装饰器:
def singleton(cls): instances = {} def get_instance(): if cls not in instances: instances[cls] = cls() return instances[cls] return get_instance @singleton class Foo: def __init__(self): pass class Bar: def __init__(self): pass f = Foo() m = Foo() print f,m,f == m a = Bar() b = Bar() print a,b,a == b
result is :
<__main__.Foo instance at 0x103152c20> <__main__.Foo instance at 0x103152c20> True
<__main__.Bar instance at 0x103152c68> <__main__.Bar instance at 0x103152cb0> False
@singleton这个装饰器实现了类的单例模式,可以确保类只会被实例化一次。
使用装饰器对参数以及方法返回结果的验证方法:
#-*-coding:utf-8-*- def accepts(*types): def check_accepts(f): # assert len(types) == f.func_code.co_argcount def new_f(*args, **kwds): for (a, t) in zip(args, types): assert isinstance(a, t), \ "arg %r does not match %s" % (a,t) return f(*args, **kwds) new_f.func_name = f.func_name return new_f return check_accepts def returns(rtype): def check_returns(f): def new_f(*args, **kwds): result = f(*args, **kwds) assert isinstance(result, rtype), \ "return value %r does not match %s" % (result,rtype) return result new_f.func_name = f.func_name return new_f return check_returns @accepts(int, (int,float)) @returns((int,float)) def func(arg1, arg2): return arg1 * arg2 print func(1,2.0)
def check_param_isvalid(): def check(method): def check_param(*args,**kwargs): for a in args: assert isinstance(a, int),"arg %r does not match %s" % (a,int) assert a > 100000,"arg %r must gt 100000" % a return method(*args, **kwargs) return check_param return check @check_param_isvalid() def foo(*args): print args foo(200000,5000)
result:
assert a > 100000,"arg %r must gt 100000" % a
AssertionError: arg 5000 must gt 100000
引用
Design Goals:
The new syntax should
* work for arbitrary wrappers, including user-defined callables and the existing builtins classmethod() and staticmethod(). This requirement also means that a decorator syntax must support passing arguments to the wrapper constructor
* work with multiple wrappers per definition
* make it obvious what is happening; at the very least it should be obvious that new users can safely ignore it when writing their own code
* be a syntax "that ... [is] easy to remember once explained"
* not make future extensions more difficult
* be easy to type; programs that use it are expected to use it very frequently
* not make it more difficult to scan through code quickly. It should still be easy to search for all definitions, a particular definition, or the arguments that a function accepts
* not needlessly complicate secondary support tools such as language-sensitive editors and other "toy parser tools out there [12]"
* allow future compilers to optimize for decorators. With the hope of a JIT compiler for Python coming into existence at some point this tends to require the syntax for decorators to come before the function definition
* move from the end of the function, where it's currently hidden, to the front where it is more in your face [13]
The new syntax should
* work for arbitrary wrappers, including user-defined callables and the existing builtins classmethod() and staticmethod(). This requirement also means that a decorator syntax must support passing arguments to the wrapper constructor
* work with multiple wrappers per definition
* make it obvious what is happening; at the very least it should be obvious that new users can safely ignore it when writing their own code
* be a syntax "that ... [is] easy to remember once explained"
* not make future extensions more difficult
* be easy to type; programs that use it are expected to use it very frequently
* not make it more difficult to scan through code quickly. It should still be easy to search for all definitions, a particular definition, or the arguments that a function accepts
* not needlessly complicate secondary support tools such as language-sensitive editors and other "toy parser tools out there [12]"
* allow future compilers to optimize for decorators. With the hope of a JIT compiler for Python coming into existence at some point this tends to require the syntax for decorators to come before the function definition
* move from the end of the function, where it's currently hidden, to the front where it is more in your face [13]
参考资料:
http://www.python.org/dev/peps/pep-0318/
http://wiki.python.org/moin/PythonDecorators
http://wiki.python.org/moin/PythonDecoratorLibrary
http://blog.csdn.net/beckel/article/details/3585352
http://blog.csdn.net/beckel/article/details/3945147
http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html
http://mrcoles.com/blog/3-decorator-examples-and-awesome-python/
http://stackoverflow.com/questions/308999/what-does-functools-wraps-do
发表评论
-
macos 10.9.2 clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command
2014-03-25 19:13 1725方法总是有的,当然需要你去寻找。 当然如果花费太多的时间在一件 ... -
PostgreSQL psycopg2:IndexError: tuple index out of range
2014-01-09 17:04 2189Postgresql psycopg2使用like查询的时候 ... -
Python 迭代器和生成器
2013-10-15 23:09 2810迭代器 迭代器只不过是一个实现迭代器协议的容器对象。它基于两个 ... -
Python时间模块
2013-10-15 23:03 3426time模块 时间模块中最常用的一个函数就是获取当前时间的函数 ... -
Python装饰器
2013-10-15 22:59 1510编写自定义装饰器有许多方法,但最简单和最容易理解的方法是编写一 ... -
python list
2013-10-15 22:56 1215简单总结以及整理如下: >>> dir( ... -
Python Excel
2013-09-10 17:21 933安装lib easy_install xlrd def ... -
排序算法学习(python版本)之堆排序(HeapSort)
2013-07-01 22:54 1959Contains: 堆排序以及堆排序的应用 堆排序(Heaps ... -
python range xrange
2013-06-25 23:30 1106引用Help on built-in function ran ... -
python class
2013-06-25 00:54 1789引用类是创建新对象类 ... -
AttributeError: 'module' object has no attribute 'SendCloud'
2013-06-05 11:46 7020网上查了下 意思是说你命名的文件名不能和lib重名,这样会导 ... -
python string
2013-05-07 23:44 2162如果这就是字符串,这本来就是字符串 首先看下字符串的方法 ... -
Python property
2013-03-29 19:56 0由于之前有总结过,可以参考http://2057.iteye. ... -
python tips
2013-03-28 23:57 8471、enum #!/usr/bin/env python ... -
python closures
2013-03-28 22:09 1152Closure:如果在一个内部函数里,对在外部作用域(但不是在 ... -
Python map、filter,reduce介绍
2013-03-28 22:02 12441、filter(function,iterable) 引用C ... -
Python __new__ 、__init__、 __call__
2013-03-26 23:49 5295Contains: __new__: 创建对象时调用,返回当 ... -
Python socket简介
2013-03-25 23:42 2118自豪地使用dir和help. Python 2.7.2 ( ... -
Tornado ioloop源码简析
2013-03-21 00:18 2801#!/usr/bin/env python #-*-en ... -
Tornado httpserver 源码简析
2013-03-17 01:49 1744整个流程就是创建一个socket socket.socket ...
相关推荐
各类速查表汇总-Python Decorators Decorators 基础命令速查
python_articles 收集一些python好文章 Parallelism in one line A Guide to Python Frameworks for Hadoop Python, C-Python, Cython代码与GIL的交互 用 ElementTree 在 Python 中解析 XML Decorators I: ...
python方法 python_装饰器Decorators
Get a comprehensive, in-depth introduction to the core Python language with this hands-on book....Learn advanced Python tools, including decorators, descriptors, metaclasses, and Unicode processing
资源分类:Python库 所属语言:Python 资源全名:lambda-decorators-0.1.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
Learning Python, Fifth Edition by Mark Lutz Get a comprehensive, in-depth introduction to the core...- Learn advanced Python tools, including decorators, descriptors, metaclasses, and Unicode processing
If you want to write efficient, high-quality code that's easily integrated with other languages and tools, this hands-on book ... including decorators, descriptors, metaclasses, and Unicode processing
python库。 资源全名:comapsmarthome-lambda-decorators-1.0.1.tar.gz
python库。 资源全名:aws-lambda-decorators-0.51.tar.gz
Make and use effective decorators and methods, including abstract, static, and class methods Employ Python for functional programming using generators, pure functions, and functional functions ...
This book is designed for Python 2 developers who want to get to grips ... Metaprogramming And Decorators Chapter 14. Fit And Finish – Unit Testing, Packaging, And Documentation Chapter 15. Next Steps
Master the secret tools every Python programmer needs to know Professional Python goes beyond the basics to teach beginner- and intermediate-level Python programmers the little-known tools and ...
It covers how to create different decorators, generators, and metaclasses. It also introduces you to functools.wraps and coroutines and how they work. Later on you will learn to use asyncio module ...
使用Python decorators特性,函数可以被编译成原生机器码,虽然这一特性会带来大约2倍的内存消耗,但也使python有更快的执行速度。 函数编译可设置使用底层整数代替python内建对象作为数字使用。有些代码的运行效率...
资源分类:Python库 所属语言:Python 资源全名:aws_lambda_decorators-0.32-py3-none-any.whl 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
python库,解压后可用。 资源全名:aws_lambda_decorators-0.45-py3-none-any.whl
python库,解压后可用。 资源全名:kafka_client_decorators-0.9.2-py3-none-any.whl
and on new, advanced tools introduced in Python 2.2 and following releases (custom descriptors, decorators, metaclasses). Each chapter contains an introduction, written by an expert in the field, ...