Transferred from: http://www.cnblogs.com/xybaby/p/6274283.html
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:https://www.python.org/dev/peps/pep-0318/#syntax-alternativescreating a singleton in Python:http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
Python Decorator Advanced