2

有谁知道我如何让下面的代码工作?

def mixin(TargetClass, *args, **kwargs):
    """*args is a bunch of classes to mixin to the TargetClass"""
    if kwargs.get('name') is None:
        kwargs['name'] = '%s_mixed_with_%s' % (TargetClass.__name__, "".join(map(str, args)))

    class MixedClass(TargetClass, *args):
        pass

    MixedClass.__name__ = kwargs.get('name')
    return MixedClass

# assume for all intents and purposes that Foo, Bar, Baz, Bot, Quux, and Muck are Classes
# Foo should inherit from all of Bar, Baz, Bot, Quux, and Muck
def uber_foo = mixin(Foo, Bar, Baz, Bot, Quux, Muck, name="UberFoo")`

现在 Python 解释器 (2.7.5) 引发以下错误:

TypeError:调用元类基类时出错元类冲突:派生类的元类必须是其所有基类的元类的(非严格)子类

4

1 回答 1

5

怎么样:

return type(kwargs.get('name'),(TargetClass,)+args,{})

代替:

class MixedClass(TargetClass, *args):
    pass

MixedClass.__name__ = kwargs.get('name')
return MixedClass

当然,您脚本的最后一行可能会引发 a SyntaxErrorasdef whatever = something无效。那应该是:

UberFoo = mixin(Foo,Bar,Baz,Bot,Quux,Muck,name='UberFoo')
于 2013-06-18T16:18:51.647 回答