Python Decorator Advanced

Source: Internet
Author: User
Tags python decorator

Transferred from:

At the beginning of the previous article, I mentioned

"In general, an adorner is a function that takes a function (or class) as a parameter, and the return value is also a function (or parameter)"

There is a general situation, there is a special case. The first special case: the adorner may also be a class; The second special case: the type of the object returned by the adorner is not necessarily the same as the type of the adorned object.

For the first case, we know that for any callable object to be called (using parentheses after the object name), the scope of the callable object is wider.
(user-defined functions, built- in functions, methods of built-inclassclass  Classobject types).

Functions (methods) and classes are callable, which is well understood, and if a class defines the __call__ method, then instances of that class are also callable. Other than that

@dec def func ():p is equivalent to: func = Dec (func), so if Dec is a class, then Dec (func) is reasonable, and the decorated Func becomes an instance of the Dec class, if the Dec class defines __call__, then the with func (*) is also reasonable, let's look at the modified code
classCost_time_logger (Object): Def __init__ (Self, func): Self.func=func def __call__ (self,*args, * *Kwargs): Import time Begin=time.time ()Try:            returnSelf.func (*args, * *Kwargs)finally: Print ('func%s cost%s'% (self.func.__name__, time.time ()-begin)) @cost_time_loggerdef complex_func (num): RET=0     forIinchxrange (num): RET+ = i *Ireturnretif__name__ = ='__main__': Print Complex_func (100000)

The function and code snippet 0 of the previous article are the same, but the type (complex_func) becomes <class ' __main__.cost_time_logger '; This also illustrates the second case where the decorated object was originally a function and was decorated to become a class instance.

In pep-0318, an example of using an adorner to implement a singleton is shown in the code below
def Singleton (CLS):     = {}    def getinstance ():        if in instances:            = cls ()         return Instances[cls]     return getinstance @singleton class MyClass:     if ' __main__ ' :    Print type (MyClass)

MyClass is a class that was decorated and turned into a function. The author is not very fond of this kind of change is the type of decoration object implementation method, this The implementation is not very friendly to the reader of the Code, and may produce some puzzling bugs, wasting debug time。 For the singleton example, there are other implementations on the StackOverflow. references:pep-0318: a singleton in Python:

Python Decorator Advanced

Related Article

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: 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.