What is a decorator used for?
Possible Duplicate:
Understanding Python decorators
Many documents online concern about the syntax of decorator. But I want to know where and how is the decorator used? Is the decorator just used to execute extra codes before and after the decorated function? Or maybe there is other usage?
The decorator syntax is powerful:
@decorator
def foo(...):
...
is equivalent to
def foo(...):
...
foo = decorator(foo)
That means that decorators can do basically anything -- they don't have to have any relation to the decorated function! Examples include:
functools.lru_cache
) property
) staticmethod
) A good practical example would be from Python's very own unittest framework where it makes use of decorators to skip tests and expected failures:
Skipping a test is simply a matter of using the skip() decorator or one of its conditional variants.
Basic skipping looks like this:
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
An decorator wraps around an method or even a whole class and delivers the ability to manipulate for example the call of an method. I very often use an @Singleton decorator to create an singleton.
Decorators are extremely powerful and really cool concept.
Look at this book for understanding them: http://amzn.com/B006ZHJSIM
链接地址: http://www.djcxy.com/p/23810.html下一篇: 什么是装饰者用于?