How to use the Mixin design mode for Python programming

Source: Internet
Author: User
Mixin mode is a kind of pattern that is used frequently in Python, and reasonable application can reach the reuse code and organize the code structure.

Python's mixin pattern can be implemented in a multi-inheritance way, for example, by customizing a simple data container with nested structures:

Class Simpleitemcontainer (object):  def __init__ (self, ID, item_containers):    self.id = id    self.data = {} For    item in Item_containers:      self.data[item.id] = Item

Simpleitemcontainer uses Python's built-in type dict to hold data, but so far it has been a direct call to the dictionary inside to access the data from the exposed API as easily as the native dictionary. Of course, the complete dictionary interface can be fully implemented from scratch, but in each of the custom similar containers, it's a good idea to take advantage of Python's built-in userdict.dictmixin:

From userdict import dictmixin

Class Bettersimpleitemcontainer (object, dictmixin):  def __getitem__ (self, id):    return Self.data[id]  def __setitem__ (self, ID, value):   self.data[id] = value  def __delitem__ (self, id):   del Self.data[id]  def keys (self):      return Self.data.keys ()

By implementing the minimal dictionary Interface and inheriting the dictmixin implementation of the mixin pattern, we easily get the full native dictionary behavior: The following table syntax, GET, Has_keys, Iteritems, Itervalues even has a series of methods and implementations such as iterable protocol implementation.

Many frameworks, such as Django, are commonly used in the Django Rest framework to mixin this pattern, when you define APIs or Viewset, and you can take some features in multiple inheritance.

Of course, the Mixin model can not be abused, at least he will pollute your new definition of the class, and sometimes bring the problem of MRO, but some basic and single functions such as the general wish to be implemented by Interface/protocol into the Mixin module is still a good choice:

Class Commonequalitymixin (object):  def __eq__ (self, Other):    return (Isinstance (other, self.__class__)      and self.__dict__ = = other.__dict__)  def __ne__ (self, Other):    return not self.__eq__ (other) class Foo ( Commonequalitymixin):  def __init__ (self, item):    Self.item = Item

In fact, the whole understanding is nothing more than a combination of ways to get more functions, a bit like C #, Java inside the interface, emphasizing the meaning of "it can", but compared to a lot simpler, do not need to display the constraints, and the Mixin module comes with the implementation. In the use of the general Mixin class on the right side of the parent also seems to emphasize that this is not a typical multi-inheritance, is a special multi-inheritance, but on the basis of inheriting a base class, incidentally, using the function of multiple inheritance to add some material to this sub-class, add some other functions. To ensure that the class function of mixin is single and concrete, the new class MRO tree will be relatively simple and will not cause confusion.

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