The main research in this paper is the implementation of the Decorator mode by python, which is described as follows. In general,

, the decorator is a function that accepts a function (or class) as a parameter, and the return value is also a function (or class). First look at a simple example:

 coding: UTF-8 # -*- -*- def log_cost_time (func): def wrapped (*args, **kwargs): import time begin time.time (try:) return = func (*args, **kwargs) finally: print'func%s cost%s'(func.__name__, time.time)% (- begin) return wrapped @log_cost_time def complex_func (Num): RET = 0 for I in xrange (Num): RET = I * I return RET #complex_func log_cost_time (complex_func) if = __name__ = ='__main__': print complex_func (100000) code snippet 0

code, log_cost_time function is a decorative device, its function is very simple, is decorated with print function run time. The syntax of the

decorator is as follows:

 @dec def func (): pass

is essentially equivalent to: func = Dec.

has the same effect in the above code (code snippet 0), to annotate line12 and to remove the line18's annotations. In addition, staticmethod and classmethod are the two decorators that we often use in code. If we decompile PyC, the codes we get are usually func = staticmthod (func) mode. Of course, the @ symbol is more popular, and at least one function name can be spelled at least once. The

instance code,

 #-*-coding:utf-8-*- '' '', is intent on adding some additional duties to an object dynamically. Than by subclassing for flexible ABC import ABCMeta class from '(Component): __metaclass__ = ABCMeta def __init__ (self): pass def operation (self): pass class ConcreteComponent (Component): def operation (self): print'ConcreteComponent operation...' class Decorator (Component): def (__init__ self, comp comp def: self._comp) = operation (self): pass class ConcreteDecorator (Decorator): def operation (self): self._comp.operation (self.addedBehavior) (DEF) addedBehavior (self): print'ConcreteDecorator addedBehavior... 'if __name__ = "__main__": comp = ConcreteComponent (DEC) = ConcreteDecorator (COMP) dec.operation (




== C:/Python27/ =======================
ConcreteComponent operation = RESTART:
... AddedBehavior... > > >

is based on the summary of above Python all Decorator model instance generation code, we hope to help. Interested friends can continue to refer to other relevant topics of the station, if there are shortcomings, welcome the message. Thank you for the support of our friends!

This paper fixed link: | Script Home | +Copy Link

Article reprint please specify:Python implementation of the Decorator schema instance code | Script Home

You may also be interested in these articles!