Python implements the Decorator mode instance code, pythondecorator

Source: Internet
Author: User

Python implements the Decorator mode instance code, pythondecorator

This article focuses on implementing the Decorator mode in python. The details are 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, let's 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_timedef 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

In the code, the functionlog_cost_timeIt is a decoration device, and its function is very simple. It prints the running time of the decorated function.

The decorator syntax is as follows:

@decdef func():pass

Essentially equivalent: func = dec(func) .

In the above code (code snippet 0), comment out line12, and then remove the line18 comment, which is the same effect. In addition, staticmethod and classmethod are two decorator that we often use in code. If we decompile pyc, the obtained code is usually func = staticmthod(func)This mode. Of course, the form of @ symbol is more popular. At least the alias function name can be spelled less.

Instance code

#-*-Coding: UTF-8-*-''' intent: dynamically add some additional responsibilities to an object. More flexible than generating subclass ''' from abc import ABCMetaclass 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): self. _ comp = comp def operation (self): passclass 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 ()

Result

===================================== RESTART: C: /Python27/0209.2.py ===========================
ConcreteComponent operation...
ConcreteDecorator addedBehavior...
>>>

Summary

The above is all the content of the Demo code for implementing the Decorator mode in python. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

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.