Python _ modifier mode and python decoration Mode
Decorator mode definition: dynamically add some additional responsibilities to an object.
In Python, the Decorator mode can be implemented in a way similar to other programming languages such as C ++ and Java. However, Python has far more capabilities in terms of application decoration concepts, python provides a syntax and a programming feature to enhance this feature.
First, you need to understand the concept of closures in Python: If a variable in the external scope (but not in the global scope) is referenced in an internal function, the internal function is regarded as a closure ).
def makeblod(fn): def wrapped(): return '<b>'+fn()+'</b>' return wrappeddef makeitalic(fn): def wrapped(): return '<i>'+fn()+'</i>' return wrapped@makeblod@makeitalicdef hello(): return 'hello world'print hello()
def deco(arg): def _deco(func): def __deco(): print "before %s called [%s]." % (func.__name__, arg) func() print "after %s called [%s]." % (func.__name__, arg) return __deco return _deco@deco("mymodule")def myfunc(): print "myfunc() called."myfunc()
Closure learning:
Http://blog.csdn.net/marty_fu/article/details/7679297
How should I understand the python decorator?
The so-called decorator is to wrap the function and add some additional functions for the function. The decorator is a function. The parameter is the encapsulated function and the encapsulated function is returned: You can try again:
Def d (fp): def _ d (* arg, ** karg): print "do something before fp .. "r = fp (* arg, ** karg) print" do something after fp .. "return r return _ d @ ddef f (): print" call f "# The above @ d is used to indicate the decorator and the following: # f = d (f) f () # Call f
How can I use a decorator in python?
I don't know. Maybe I can't jump out of the main function in the decorator.