module A # you create a moduledef a1 # lets have a method 'a1' in itenddef a2 # Another method 'a2'endend
module B # let's say we have another moduledef b1 # A method 'b1'enddef b2 #another method b2endend
class Sample # we create a class 'Sample'include A # including module 'A' in the class 'Sample' (mixin)include B # including module B as well
def S1 #class 'Sample' contains a method 's1'endend
samp = Sample.new # creating an instance object 'samp'
# we can access methods from module A and B in our class(power of mixin)
samp.a1 # accessing method 'a1' from module Asamp.a2 # accessing method 'a2' from module Asamp.b1 # accessing method 'b1' from module Bsamp.b2 # accessing method 'a2' from module Bsamp.s1 # accessing method 's1' inside the class Sample
class ComparableMixin(object):"""This class has methods which use `<=` and `==`,but this class does NOT implement those methods."""def __ne__(self, other):return not (self == other)def __lt__(self, other):return self <= other and (self != other)def __gt__(self, other):return not self <= otherdef __ge__(self, other):return self == other or self > other
class Integer(ComparableMixin):def __init__(self, i):self.i = idef __le__(self, other):return self.i <= other.idef __eq__(self, other):return self.i == other.i
assert Integer(0) < Integer(1)assert Integer(0) != Integer(1)assert Integer(1) > Integer(0)assert Integer(1) >= Integer(1)
# It is possible to instantiate a mixin:o = ComparableMixin()# but one of its methods raise an exception:#o != o
class OrderedCounter(Counter, OrderedDict):'Counter that remembers the order elements are first encountered'
def __repr__(self):return '%s(%r)' % (self.__class__.__name__, OrderedDict(self))
def __reduce__(self):return self.__class__, (OrderedDict(self),)
class ThreadingMixIn:"""Mix-in class to handle each request in a new thread."""
# Decides how threads will act upon termination of the# main processdaemon_threads = False
def process_request_thread(self, request, client_address):"""Same as in BaseServer but as a thread.In addition, exception handling is done here."""try:self.finish_request(request, client_address)except Exception:self.handle_error(request, client_address)finally:self.shutdown_request(request)
def process_request(self, request, client_address):"""Start a new thread to process the request."""t = threading.Thread(target = self.process_request_thread,args = (request, client_address))t.daemon = self.daemon_threadst.start()
一个虚构的例子
这是一个主要用于演示目的的混合-大多数对象将超出此repr的有用性:
class SimpleInitReprMixin(object):"""mixin, don't instantiate - useful for classes instantiableby keyword arguments to their __init__ method."""__slots__ = () # allow subclasses to use __slots__ to prevent __dict__def __repr__(self):kwarg_strings = []d = getattr(self, '__dict__', None)if d is not None:for k, v in d.items():kwarg_strings.append('{k}={v}'.format(k=k, v=repr(v)))slots = getattr(self, '__slots__', None)if slots is not None:for k in slots:v = getattr(self, k, None)kwarg_strings.append('{k}={v}'.format(k=k, v=repr(v)))return '{name}({kwargs})'.format(name=type(self).__name__,kwargs=', '.join(kwarg_strings))
和用法将是:
class Foo(SimpleInitReprMixin): # add other mixins and/or extend another class here__slots__ = 'foo',def __init__(self, foo=None):self.foo = foosuper(Foo, self).__init__()
及用法:
>>> f1 = Foo('bar')>>> f2 = Foo()>>> f1Foo(foo='bar')>>> f2Foo(foo=None)
import logging
class LoggingMixIn:def __setitem__(self, key, value):logging.info('Setting %r to %r', key, value)super().__setitem__(key, value)def __delitem__(self, key):logging.info('Deleting %r', key)super().__delitem__(key)
class LoggingList(LoggingMixIn, list):pass
class LoggingDict(LoggingMixIn, dict):pass
>>> logging.basicConfig(level=logging.INFO)>>> l = LoggingList([False])>>> d = LoggingDict({'a': False})>>> l[0] = TrueINFO:root:Setting 0 to True>>> d['a'] = TrueINFO:root:Setting 'a' to True>>> del l[0]INFO:root:Deleting 0>>> del d['a']INFO:root:Deleting 'a'