0

可能的重复:
理解 Python 装饰器

网上很多文档都关注装饰器的语法。但我想知道装饰器在哪里以及如何使用?装饰器只是用来在装饰函数之前和之后执行额外的代码吗?或者也许还有其他用途?

4

3 回答 3

3

装饰器语法很强大:

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

相当于

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

这意味着装饰器基本上可以做任何事情——它们不必与被装饰的函数有任何关系!示例包括:

  • 记忆递归函数 ( functools.lru_cache)
  • 记录对函数的所有调用
  • 实现描述符功能 ( property)
  • 将方法标记为静态 ( staticmethod)
于 2012-11-19T08:54:11.823 回答
0

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

跳过测试只需使用 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
于 2012-11-19T09:29:50.647 回答
0

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

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

看这本书来理解它们:http ://amzn.com/B006ZHJSIM

于 2012-11-19T09:30:12.413 回答