- 浏览: 248142 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (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 1769方法总是有的,当然需要你去寻找。 当然如果花费太多的时间在一件 ... -
PostgreSQL psycopg2:IndexError: tuple index out of range
2014-01-09 17:04 2234Postgresql psycopg2使用like查询的时候 ... -
Python 迭代器和生成器
2013-10-15 23:09 2854迭代器 迭代器只不过是一个实现迭代器协议的容器对象。它基于两个 ... -
Python时间模块
2013-10-15 23:03 3478time模块 时间模块中最常用的一个函数就是获取当前时间的函数 ... -
Python装饰器
2013-10-15 22:59 1573编写自定义装饰器有许多方法,但最简单和最容易理解的方法是编写一 ... -
python list
2013-10-15 22:56 1261简单总结以及整理如下: >>> dir( ... -
Python Excel
2013-09-10 17:21 980安装lib easy_install xlrd def ... -
排序算法学习(python版本)之堆排序(HeapSort)
2013-07-01 22:54 2005Contains: 堆排序以及堆排序的应用 堆排序(Heaps ... -
python range xrange
2013-06-25 23:30 1158引用Help on built-in function ran ... -
python class
2013-06-25 00:54 1832引用类是创建新对象类 ... -
AttributeError: 'module' object has no attribute 'SendCloud'
2013-06-05 11:46 7093网上查了下 意思是说你命名的文件名不能和lib重名,这样会导 ... -
python string
2013-05-07 23:44 2202如果这就是字符串,这本来就是字符串 首先看下字符串的方法 ... -
Python property
2013-03-29 19:56 0由于之前有总结过,可以参考http://2057.iteye. ... -
python tips
2013-03-28 23:57 8901、enum #!/usr/bin/env python ... -
python closures
2013-03-28 22:09 1195Closure:如果在一个内部函数里,对在外部作用域(但不是在 ... -
Python map、filter,reduce介绍
2013-03-28 22:02 13201、filter(function,iterable) 引用C ... -
Python __new__ 、__init__、 __call__
2013-03-26 23:49 5360Contains: __new__: 创建对象时调用,返回当 ... -
Python socket简介
2013-03-25 23:42 2182自豪地使用dir和help. Python 2.7.2 ( ... -
Tornado ioloop源码简析
2013-03-21 00:18 2857#!/usr/bin/env python #-*-en ... -
Tornado httpserver 源码简析
2013-03-17 01:49 1794整个流程就是创建一个socket socket.socket ...
相关推荐
Python Decorators是一种函数设计模式,允许用户在不改变原有函数定义的情况下,为函数添加额外的功能。它是在函数定义前使用@符号加上装饰器函数名的方式来实现的。装饰器本质上是一个接受函数作为参数并返回一个新...
使用Python decorators特性,函数可以被编译成原生机器码,虽然这一特性会带来大约2倍的内存消耗,但也使python有更快的执行速度。函数编译可设置使用底层整数代替python内建对象作为数字使用。有些代码的运行效率...
python_articles 收集一些python好文章 Parallelism in one line A Guide to Python Frameworks for Hadoop Python, C-Python, Cython代码与GIL的交互 用 ElementTree 在 Python 中解析 XML Decorators I: ...
0392_极智开发_解读python装饰器Decorators
### Python装饰器详解 #### 一、什么是装饰器? 装饰器是Python中一个非常重要的特性。简单来说,装饰器就是一个可以修改其他函数功能的函数。它们可以帮助我们编写更加简洁、可读性更强的代码,同时也使得代码...
**Python库aws_lambda_decorators-0.45-py3-none-any.whl详解** `aws_lambda_decorators` 是一个Python库,专为Amazon Web Services(AWS)的Lambda服务设计,用于简化函数装饰器的使用,从而更高效地开发和管理...
《Python库aws-lambda-decorators-0.51:构建高效AWS Lambda函数》 在IT行业中,Python作为一门强大的编程语言,广泛应用于各种场景,特别是在后端开发领域。随着云计算的发展,Amazon Web Services(AWS)提供的...
**Python库-kafka_client_decorators 0.9.2** `kafka_client_decorators` 是一个专门针对Python的Kafka客户端开发的装饰器库,它为处理Apache Kafka消息提供了便捷和灵活的方式。这个库的版本0.9.2是专为Python 3...
在Python中,还有许多其他高级主题,如装饰器(decorators)用于修改或增强函数行为,生成器(generators)用于创建迭代器,以及上下文管理器(context managers)用于资源的自动获取和释放,如使用with语句处理文件。...
《Python库:comapsmarthome-lambda-decorators-1.0.1》 在IT行业中,Python作为一门强大的开发语言,因其简洁易读的语法和丰富的库支持,广泛应用于后端开发、数据分析、机器学习等多个领域。本文将重点探讨名为`...
资源分类:Python库 所属语言:Python 资源全名:lambda-decorators-0.1.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
此外,装饰器(decorators)和上下文管理器(context managers)也可能出现在这些案例中,它们是Python中用于代码重用和资源管理的强大工具。 面向对象编程(OOP)是Python的另一个关键方面。案例可能涵盖类(classes)的...
7. **装饰器(Decorators)**:装饰器是Python的一种元编程技术,可以用来修改或增强函数、类的行为。理解装饰器的工作原理和使用场景,如授权、日志记录,对于编写高效代码至关重要。 8. **全局变量和返回(Return)**...
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
使用Python decorators特性,函数可以被编译成原生机器码,虽然这一特性会带来大约2倍的内存消耗,但也使python有更快的执行速度。 函数编译可设置使用底层整数代替python内建对象作为数字使用。有些代码的运行效率...
2. **装饰器(Decorators)**:装饰器是Python中的一个强大工具,可以修改或增强函数、类的行为,而不改变其原始代码。学习如何创建和使用装饰器可以提升代码的灵活性和重用性。 3. **上下文管理器(Context ...
6. **装饰器(Decorators)**: - 装饰器是Python的一种函数,用于修改或增强其他函数的功能,如添加日志、性能监控等。 - `@decorator`语法糖使得装饰器使用更加简洁。 - 装饰器可以接收参数,增加其灵活性,实现...
- **装饰器(Decorators)**:增强现有函数的功能而不修改其源代码。 ##### 6. 常用标准库 - **os模块**:提供与操作系统交互的接口。 - **re模块**:支持正则表达式的操作。 - **datetime模块**:处理日期和时间的...