In Python can one implement mixin behavior without using inheritance?

前端 未结 8 1655
醉梦人生
醉梦人生 2021-02-06 13:10

Is there a reasonable way in Python to implement mixin behavior similar to that found in Ruby -- that is, without using inheritance?

class Mixin(object):
    def         


        
8条回答
  •  天命终不由人
    2021-02-06 13:45

    EDIT: Fixed what could (and probably should) be construed as a bug. Now it builds a new dict and then updates that from the class's dict. This prevents mixins from overwriting methods that are defined directly on the class. The code is still untested but should work. I'm busy ATM so I'll test it later. It worked fine except for a syntax error. In retrospect, I decided that I don't like it (even after my further improvements) and much prefer my other solution even if it is more complicated. The test code for that one applies here as well but I wont duplicate it.

    You could use a metaclass factory:

     import inspect
    
     def add_mixins(*mixins):
         Dummy = type('Dummy', mixins, {})
         d = {}
    
         for mixin in reversed(inspect.getmro(Dummy)):
             d.update(mixin.__dict__)
    
         class WithMixins(type):
             def __new__(meta, classname, bases, classdict):
                 d.update(classdict)
                 return super(WithMixins, meta).__new__(meta, classname, bases, d)
         return WithMixins 
    

    then use it like:

     class Foo(object):
         __metaclass__ = add_mixins(Mixin1, Mixin2)
    
         # rest of the stuff
    

提交回复
热议问题