Python的装饰器

在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
    原文作者:lintong
    原文地址: https://www.jianshu.com/p/998a74fb5c85
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞