什么是装饰用于?

时间:2012-11-19 08:38:02

标签: python decorator

  

可能重复:
  Understanding Python decorators

许多文档在线关注装饰器的语法。但我想知道装饰器在哪里以及如何使用?装饰器是否仅用于在装饰函数之前和之后执行额外代码?或者可能有其他用途?

3 个答案:

答案 0 :(得分:3)

装饰器语法很强大:

@decorator
def foo(...):
    ...

相当于

def foo(...):
    ...
foo = decorator(foo)

这意味着装饰者可以基本上做任何事情 - 他们不必与装饰函数有任何关系!例子包括:

  • 记忆递归函数(functools.lru_cache
  • 记录对函数的所有调用
  • 实现描述符功能(property
  • 将方法标记为静态(staticmethod

答案 1 :(得分:0)

一个很好的实际例子来自Python自己的unittest framework,它使用装饰器来跳过测试和预期的失败:

  

跳过测试只是使用skip()装饰器或   其中一个条件变体。

     

基本跳过如下:

class MyTestCase(unittest.TestCase):

    @unittest.skip("demonstrating skipping")
    def test_nothing(self):
        self.fail("shouldn't happen")

    @unittest.skipIf(mylib.__version__ < (1, 3),
                     "not supported in this library version")
    def test_format(self):
        # Tests that work for only a certain version of the library.
        pass

    @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
    def test_windows_support(self):
        # windows specific testing code
        pass

答案 2 :(得分:0)

装饰器包装方法甚至整个类,并提供操作例如方法调用的能力。我经常使用@Singleton装饰器来创建一个单例。

装饰者是非常强大且非常酷的概念。

请阅读本书以了解它们:http://amzn.com/B006ZHJSIM

相关问题