python,python decorators

Decorator is a very expressive language feature in python. It helps developers to write cleaner, modular code that is easier to extend and maintain. It also helps implement AOP and decorator pattern in python.

Decorator syntax
To declare a decorator function, we can define a function that takes a another function as argument and returns a function. The usage of decorator is very simple, just add a line begins with '@' symbol and the name of the decorator before the function to be decorated.


 1 def decorator(func):
 2     def new_func():
 3         print "decorator message"
 4         func()
 5     return new_func
 6
 7 @decorator
 8 def foo():
 9     print "hello world"
10
11 foo()

Tags:  python平台 python

延伸阅读

最新评论

发表评论