创建一个继承其所在类的动态类

时间:2018-01-23 15:20:37

标签: python

当我尝试在父类中创建一个类时,子类继承了' 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

            [...]

我确信这在某种程度上是可能的;有什么建议吗?

1 个答案:

答案 0 :(得分:2)

进行以下更改

...
if self.create_proxy:    
    class Proxy(SomeMixin, A): #use class name instead of self
        pass
...

还要确保SomeMixinobject的子类,否则会导致元类冲突。

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