Python Decorator Learning (decorator)

Source: Internet
Author: User

Recently saw an example of a decorator, not read,

#!/usr/bin/pythonclassDecorator (object):def __init__(self,f):Print "Initial Decorator"f ()def __call__(self):Print "Call Decorator"@decoratordefFun ():Print " in the fun"Print " After"Fun ()

See the most viewed articles about Python decorators from StackOverflow, here's the URL of this article

http://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python/1594484#1594484

Feel write very good, I also summarize summary.

The problem is that LZ wants to write an adorner:

@makebold @makeitalic def say ():    return " Hello "

There is such an output:

"<b><i>Hello</i></b>"

See the shortest reply is:

defMakebold (f):return Lambda:"<b>"+ f () +"</b>"defMakeitalic (f):return Lambda:"<i>"+ f () +"</i>"@makebold @makeitalicdefsay ():return "Hello"PrintSay ()

It's so classic,

For the first example, write the snippet code:

#de on behalf of decorator Bar, simple O (∩_∩) o~,
Def de (f):
def WR ():
Print "Before Func"
F ()
Print "After Func"
Return WR

def func ():
Print "This is the Func self"
#先运行一遍代码
Func ()
#装饰函数
De_func=de (func)
#运行装饰了之后的函数
De_func ()
#或者
#装饰函数
Func=de (func)
#运行装饰了之后的函数
Func ()
#或者
De (func) ()

Another thing to understand is that the __call__ method of a class is called when the Instance=classname () () () (also written as Instance=classname (), instance ()) is used.

Python's own decorator is:

#还可以在函数定义之前加上 @de @dedef func1 ():    print "**this is func-Self" func1 ()

Understanding the above example of the beginning of the article can also be written like this

Class Decorator (object):    def __init__ (self,f):        print "initial decorator"        F ()    def __call__ (self):        print "Call decorator" # @decoratordef Fun ():    print ' In the fun ' Fun=decorator (fun) print ' after ' fun ()

Have a careful look at the article, feeling benefited, but also when they learned the time did not listen to it.

       

Python Decorator Learning (decorator)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.