在Python中可以实现mixin行为而不使用继承吗?

FMc*_*FMc 4 ruby python inheritance mixins

在Python中是否有合理的方法来实现类似于Ruby中的mixin行为 - 也就是说,不使用继承?

class Mixin(object):
    def b(self): print "b()"
    def c(self): print "c()"

class Foo(object):
    # Somehow mix in the behavior of the Mixin class,
    # so that all of the methods below will run and
    # the issubclass() test will be False.

    def a(self): print "a()"

f = Foo()
f.a()
f.b()
f.c()
print issubclass(Foo, Mixin)
Run Code Online (Sandbox Code Playgroud)

我有一个模糊的想法,与类装饰师这样做,但我的尝试导致混乱.我对该主题的大多数搜索都指向了使用继承(或者在更复杂的场景中,多重继承)来实现mixin行为.

Joh*_*ooy 9

def mixer(*args):
    """Decorator for mixing mixins"""
    def inner(cls):
        for a,k in ((a,k) for a in args for k,v in vars(a).items() if callable(v)):
            setattr(cls, k, getattr(a, k).im_func)
        return cls
    return inner

class Mixin(object):
    def b(self): print "b()"
    def c(self): print "c()"

class Mixin2(object):
    def d(self): print "d()"
    def e(self): print "e()"


@mixer(Mixin, Mixin2)
class Foo(object):
    # Somehow mix in the behavior of the Mixin class,
    # so that all of the methods below will run and
    # the issubclass() test will be False.

    def a(self): print "a()"

f = Foo()
f.a()
f.b()
f.c()
f.d()
f.e()
print issubclass(Foo, Mixin)
Run Code Online (Sandbox Code Playgroud)

输出:

a()
b()
c()
d()
e()
False
Run Code Online (Sandbox Code Playgroud)