In Python can one implement mixin behavior without using inheritance?

前端 未结 8 1498
醉梦人生
醉梦人生 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:44

    You could decorate the classes __getattr__ to check in the mixin. The problem is that all methods of the mixin would always require an object the type of the mixin as their first parameter, so you would have to decorate __init__ as well to create a mixin-object. I believe you could achieve this using a class decorator.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题