python装饰器

方法上的装饰器:

https://eastlakeside.gitbooks.io/interpy-zh/content/decorators/deco_class.html#

装饰器给类扩充功能

http://python3-cookbook.readthedocs.io/zh_CN/latest/c09/p12_using_decorators_to_patch_class_definitions.html

def log_request_decorator(cls):
    # Get the original implementation
    # orig_do_log = cls.__do_log

    # Make a new definition
    def log_request(self, handler):
        from tornado.log import access_log
        if handler.get_status() < 400:
            log_method = access_log.info
        elif handler.get_status() < 500:
            log_method = access_log.warning
        else:
            log_method = access_log.error
        request_time = 1000.0 * handler.request.request_time()
        log_method("%d %s %s %.2fms 
Headers:%s", handler.get_status(),
                   handler._request_summary(), handler.request.body, request_time, handler.request.headers)

    # Attach to the class and return
    cls.log_function = log_request
    return cls




@logutils.log_request_decorator
class BillingService(ServiceBase):
  def log_function(self, handler):
    do something
.......

  

原文地址:https://www.cnblogs.com/peterpanzsy/p/6913693.html