Python的装饰器

作者: lintong | 来源:发表于2015-02-11 11:54 被阅读128次

在Python中,函数是一等对象,因此你可以将函数与字符串,整数等对象看成一样。
比如你可以将函数赋值给一个变量:

>>> def square(n):
...     return n * n
>>> square(4)
16
>>> alias = square
>>> alias(4)
16

函数作为一等对象的作用在于,你可以将函数作为参数传递给另外一个函数,或者从另外一个函数中返回。比如Python内建的map函数:

you pass it a function and a list, and map creates a new list by calling your function individually for each item in the list you gave it. Here’s an example that uses our square function from above:

>>> numbers = [1, 2, 3, 4, 5]
>>> map(square, numbers)
[1, 4, 9, 16, 25]

接受函数作为参数或者返回函数的函数被称为:higher-order function。我们可以使用higher-order函数来改变传入的函数的对外行为。

比如:假设我们有一个函数,该函数的会被频繁的调用,因此开销非常大。

>>> def fib(n):
...     "Recursively (i.e., dreadfully) calculate the nth Fibonacci number."
...     return n if n in [0, 1] else fib(n - 2) + fib(n - 1)

最好的方法是保存函数的计算结果,因此如果我们需要计算一个n的函数值,不需要反复计算n之前的值。
有很多种方式来实现保存计算结果,比如可以使用一个dictionary。但是这需要外部来保存这些计算结果,这样会造成一定的紧耦合。因此如果fib函数自身保存计算的结果,外部只需要调用这个函数就可以了。这种技术叫做:memorization

Python采用一种装饰器的方式来实现 memorization,因为我们可以将函数作为参数传递给另外一个函数,因此我们可以写一个通用的外部函数,该函数接收一个函数参数并返回一个带有memorized版本。

def memoize(fn):
    stored_results = {}
    def memoized(*args):
        try:
            # try to get the cached result
            return stored_results[args]
        except KeyError:
            # nothing was cached for those args. let's fix that.
            result = stored_results[args] = fn(*args)
            return result
    return memoized

有了带有memorization版本的函数,可以这样调用:

def fib(n):
   return n if n in [0, 1] else fib(n - 2) + fib(n - 1)
fib = memoize(fib)

而这里还可以采用decorator来简写:

@memoize
def fib(n):
   return n if n in [0, 1] else fib(n - 2) + fib(n - 1)

如果一个函数有多个装饰器,则他们采用从底部到顶部的方式起作用。比如假设我们还有一个higher-order函数来帮助调试。

def make_verbose(fn):
    def verbose(*args):
        # will print (e.g.) fib(5)
        print '%s(%s)' % (fn.__name__, ', '.join(repr(arg) for arg in args))
        return fn(*args) # actually call the decorated function
    return verbose

下面两个形式的代码片段做同样的事情:

@memoize
@make_verbose
def fib(n):
    return n if n in [0, 1] else fib(n - 2) + fib(n - 1)
def fib(n):
    return n if n in [0, 1] else fib(n - 2) + fib(n - 1)
fib = memoize(make_verbose(fib))

更加有趣的是,你可以给装饰器传递额外的参数。比如我们不满足一些简单的memorization,而是想要存储函数结果到memcached中,因此需要给装饰器传入memcached的服务器地址等参数信息。

@memcached('127.0.0.1:11211')
def fib(n):
    return n if n in [0, 1] else fib(n - 2) + fib(n - 1)

上述代码等价于:

fib = memcached('127.0.0.1:11211')(fib)

Python有些内建的装饰器函数,比如:classmethod装饰器,该装饰器下的函数等价于java中的静态函数。

class Foo(object):
    SOME_CLASS_CONSTANT = 42

    @classmethod
    def add_to_my_constant(cls, value):
        # Here, `cls` will just be Foo, but if you called this method on a
        # subclass of Foo, `cls` would be that subclass instead.
        return cls.SOME_CLASS_CONSTANT + value

Foo.add_to_my_constant(10) # => 52

# unlike in Java, you can also call a classmethod on an instance
f = Foo()
f.add_to_my_constant(10) # => 52

相关文章

  • 装饰器模式

    介绍 在python装饰器学习 这篇文章中,介绍了python 中的装饰器,python内置了对装饰器的支持。面向...

  • [译] Python装饰器Part II:装饰器参数

    这是Python装饰器讲解的第二部分,上一篇:Python装饰器Part I:装饰器简介 回顾:不带参数的装饰器 ...

  • Python中的装饰器

    Python中的装饰器 不带参数的装饰器 带参数的装饰器 类装饰器 functools.wraps 使用装饰器极大...

  • Python进阶——面向对象

    1. Python中的@property   @property是python自带的装饰器,装饰器(decorat...

  • python中的装饰器

    python装饰器详解 Python装饰器学习(九步入门) 装饰器(decorator) 就是一个包装机(wrap...

  • Python 装饰器填坑指南 | 最常见的报错信息、原因和解决方

    Python 装饰器简介装饰器(Decorator)是 Python 非常实用的一个语法糖功能。装饰器本质是一种返...

  • python3基础---详解装饰器

    1、装饰器原理 2、装饰器语法 3、装饰器执行的时间 装饰器在Python解释器执行的时候,就会进行自动装饰,并不...

  • Python装饰器

    Python装饰器 一、函数装饰器 1.无参装饰器 示例:日志记录装饰器 2.带参装饰器 示例: 二、类装饰器 示例:

  • 2019-05-26python装饰器到底是什么?

    装饰器例子 参考语法 装饰器是什么?个人理解,装饰器,是python中一种写法的定义。他仍然符合python的基本...

  • 2018-07-18

    Python装饰器 装饰,顾名思义,是用来打扮什么东西的。Python装饰...

网友评论

    本文标题:Python的装饰器

    本文链接:https://www.haomeiwen.com/subject/pqijxttx.html