In Python can one implement mixin behavior without using inheritance?

前端 未结 8 1506
醉梦人生
醉梦人生 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条回答
  •  旧时难觅i
    2021-02-06 13:43

    from functools import partial
    class Mixin(object):
        @staticmethod
        def b(self): print "b()"
        @staticmethod
        def c(self): print "c()"
    
    class Foo(object):
        def __init__(self, mixin_cls):
            self.delegate_cls = mixin_cls
    
        def __getattr__(self, attr):
            if hasattr(self.delegate_cls, attr):
                return partial(getattr(self.delegate_cls, attr), self)
    
        def a(self): print "a()"
    
    f = Foo(Mixin)
    f.a()
    f.b()
    f.c()
    print issubclass(Foo, Mixin)
    

    This basically uses the Mixin class as a container to hold ad-hoc functions (not methods) that behave like methods by taking an object instance (self) as the first argument. __getattr__ will redirect missing calls to these methods-alike functions.

    This passes your simple tests as shown below. But I cannot guarantee it will do all the things you want. Make more thorough test to make sure.

    $ python mixin.py 
    a()
    b()
    c()
    False
    

提交回复
热议问题