`

python decorators

阅读更多
Contains:
  • 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]



参考资料:
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
分享到:
评论

相关推荐

    各类速查表汇总-Python Decorators

    Python Decorators是一种函数设计模式,允许用户在不改变原有函数定义的情况下,为函数添加额外的功能。它是在函数定义前使用@符号加上装饰器函数名的方式来实现的。装饰器本质上是一个接受函数作为参数并返回一个新...

    572、MicroPython开发板资料(原理图、PCB图、源代码)

    使用Python decorators特性,函数可以被编译成原生机器码,虽然这一特性会带来大约2倍的内存消耗,但也使python有更快的执行速度。函数编译可设置使用底层整数代替python内建对象作为数字使用。有些代码的运行效率...

    程序员面试究竟要不要刷题-Python_Articles:收集一些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

    0392_极智开发_解读python装饰器Decorators

    python-装饰器Decorators.pdf

    ### Python装饰器详解 #### 一、什么是装饰器? 装饰器是Python中一个非常重要的特性。简单来说,装饰器就是一个可以修改其他函数功能的函数。它们可以帮助我们编写更加简洁、可读性更强的代码,同时也使得代码...

    Python库 | aws_lambda_decorators-0.45-py3-none-any.whl

    **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.tar.gz

    《Python库aws-lambda-decorators-0.51:构建高效AWS Lambda函数》 在IT行业中,Python作为一门强大的编程语言,广泛应用于各种场景,特别是在后端开发领域。随着云计算的发展,Amazon Web Services(AWS)提供的...

    Python库 | kafka_client_decorators-0.9.2-py3-none-any.whl

    **Python库-kafka_client_decorators 0.9.2** `kafka_client_decorators` 是一个专门针对Python的Kafka客户端开发的装饰器库,它为处理Apache Kafka消息提供了便捷和灵活的方式。这个库的版本0.9.2是专为Python 3...

    Python-一些Python示例

    在Python中,还有许多其他高级主题,如装饰器(decorators)用于修改或增强函数行为,生成器(generators)用于创建迭代器,以及上下文管理器(context managers)用于资源的自动获取和释放,如使用with语句处理文件。...

    Python库 | comapsmarthome-lambda-decorators-1.0.1.tar.gz

    《Python库:comapsmarthome-lambda-decorators-1.0.1》 在IT行业中,Python作为一门强大的开发语言,因其简洁易读的语法和丰富的库支持,广泛应用于后端开发、数据分析、机器学习等多个领域。本文将重点探讨名为`...

    Python库 | lambda-decorators-0.1.tar.gz

    资源分类:Python库 所属语言:Python 资源全名:lambda-decorators-0.1.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

    python趣味编程100例(99个)

    此外,装饰器(decorators)和上下文管理器(context managers)也可能出现在这些案例中,它们是Python中用于代码重用和资源管理的强大工具。 面向对象编程(OOP)是Python的另一个关键方面。案例可能涵盖类(classes)的...

    Python进阶教程 Python各知识领域高级操作教程 进阶操作教程 共26个章节 共103页.pdf

    7. **装饰器(Decorators)**:装饰器是Python的一种元编程技术,可以用来修改或增强函数、类的行为。理解装饰器的工作原理和使用场景,如授权、日志记录,对于编写高效代码至关重要。 8. **全局变量和返回(Return)**...

    Learning Python 5th Edition(Python学习手册,第5版,英文)

    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进阶.pdf

    6. **装饰器(Decorators)**: - 装饰器是Python的一种函数,用于修改或增强其他函数的功能,如添加日志、性能监控等。 - `@decorator`语法糖使得装饰器使用更加简洁。 - 装饰器可以接收参数,增加其灵活性,实现...

    (DIY设计)MicroPython开发板原理图+PCB源文件+源代码等-电路方案

    使用Python decorators特性,函数可以被编译成原生机器码,虽然这一特性会带来大约2倍的内存消耗,但也使python有更快的执行速度。 函数编译可设置使用底层整数代替python内建对象作为数字使用。有些代码的运行效率...

    Python高級编程_python进阶_python高级编程_

    2. **装饰器(Decorators)**:装饰器是Python中的一个强大工具,可以修改或增强函数、类的行为,而不改变其原始代码。学习如何创建和使用装饰器可以提升代码的灵活性和重用性。 3. **上下文管理器(Context ...

    Python in a Nutshell Third Edition 2017

    - **装饰器(Decorators)**:增强现有函数的功能而不修改其源代码。 ##### 6. 常用标准库 - **os模块**:提供与操作系统交互的接口。 - **re模块**:支持正则表达式的操作。 - **datetime模块**:处理日期和时间的...

Global site tag (gtag.js) - Google Analytics