当我尝试在父类中创建一个类时,子类继承了' self',我收到以下错误:
TypeError: Error when calling the metaclass bases
metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
class A(object):
create_proxy = False
def __init__(self, *args, **kwargs):
super(A, self).__init__(*args, **kwargs)
if self.create_proxy:
class Proxy(SomeMixin, self):
pass
[...]
我确信这在某种程度上是可能的;有什么建议吗?
答案 0 :(得分:2)
进行以下更改
...
if self.create_proxy:
class Proxy(SomeMixin, A): #use class name instead of self
pass
...
还要确保SomeMixin
是object
的子类,否则会导致元类冲突。
class SomeMixin(object):
pass
class A(object):
create_proxy = True #False
def __init__(self, *args, **kwargs):
super(A, self).__init__(*args, **kwargs)
if self.create_proxy:
class Proxy(SomeMixin, A):
pass
a = A() #test