有谁知道如何让以下代码工作?
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:调用元类库时出错 元类冲突:派生类的元类必须是其所有基类的元类的(非严格)子类
答案 0 :(得分:5)
怎么样:
return type(kwargs.get('name'),(TargetClass,)+args,{})
而不是:
class MixedClass(TargetClass, *args):
pass
MixedClass.__name__ = kwargs.get('name')
return MixedClass
当然,由于SyntaxError
无效,您脚本的最后一行可能会引发def whatever = something
。那应该是:
UberFoo = mixin(Foo,Bar,Baz,Bot,Quux,Muck,name='UberFoo')