Python class as decorator

Source: Internet
Author: User

The official description of decorator is as follows: (http://docs.python.org/glossary.html)

Decorator

A function returning another function, usually applied as a function transformation using@ WrapperSyntax. Common examplesDecoratorS areClassmethod ()AndStaticmethod ().

TheDecoratorSyntax is merely syntactic sugar, the following two function definitions are semantically equivalent:

Def F(...):...F = Staticmethod(F)@ StaticmethodDef F(...):...

The same concept exists for classes, but is less commonly used there. See the documentationFunction definitionsAndClass definitionsFor more aboutDecoratorS.

Here only demonstrates the use of a class as the decorator, in fact, the main class to contain _ call _ method, the _ call _ can refer to here http://www.cnblogs.com/john2000/archive/2012/03/27/2418981.html

 

# Encoding: UTF-8 "Class As decorator" Import timeclass A: def _ init _ (self, func ): print "_ init _" def _ call _ (Self): time. sleep (10) print "_ call _" @ adef test (): # the compiler will interpret this as instancea = a (test ), when we call test, we actually call instancea (* ARGs), that is, instancea. _ call _ (* ARGs)
 
Print "test" If _ name _ = "_ main _": Test ()

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.