Python _ modifier mode and python decoration Mode

Source: Internet
Author: User

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.

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.