Python装饰器的典型应用和用例

时间:2012-04-12 12:12:04

标签: python python-3.x python-2.7

虽然最近在Python装饰器上阅读了这个article,但它给出了memoization作为Python装饰器应用程序的技术。虽然我对Python装饰器有了一定的了解,但我想知道装饰器的更多有效用例,以及如何在日常代码中使用它们。

4 个答案:

答案 0 :(得分:2)

有许多内置装饰器非常有用,例如classmethodpropertystaticmethodfunctools.wrap。编写一个装饰器来记录函数的使用以进行调试通常很方便。 this Python wiki page上有很多示例装饰器,但我认为其中至少有一些更多旨在展示Python的灵活性,而不是实际提供有用的功能。

答案 1 :(得分:1)

由于Python 3支持类型注释,因此可以使用装饰器作为检查方式。

def check(f):
    def _f(x):
        if type(x) != f.__annotations__['x']:
            raise TypeError(type(x))
        val = f(x)
        if 'return' in f.__annotations__ and f.__annotations__['return'] != type(val):
            raise TypeError(type(val))
        return val
    return _f

@check
def f(x: int) -> int:
    return x * 2

>>> f(2)
4

>>> f('x')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in _f
TypeError: <class 'str'>

答案 2 :(得分:0)

您可以在Django Web框架auth docs中查看python装饰器的有效用例。清楚的例子(我个人日常使用)包括restricting views to authenticated usersrestricting access depending on specific user permissions等装饰器的使用。

答案 3 :(得分:0)

这是一个实际的例子。看一下斐波那契的系列总和,无论是否有备忘录。

from functools import wraps
def memo(func): 
    cache = {}
    @wraps(func)
    def wrap(*args):
        if args not in cache: 
            cache[args] = func(*args)
        return cache[args] 
    return wrap

def fib(i):
    if i < 2: return 1
    return fib(i-1) + fib(i-2)

@memo
def fib_memo(i):
    if i < 2: return 1
    return fib_memo(i-1) + fib_memo(i-2)

现在测试速度差异了!

>>> print fib(200)
...
>>> print fib_memo(200)
...