在Python的嵌套类中,访问外部类父类的最佳方法是什么?

时间:2018-01-26 16:46:21

标签: python django inheritance nested inner-classes

我有一个非常简单的Django系统,并且还有很多Meta类继承。归结为它的本质看起来像这样:

class Base:
    class Meta:
        pass

class Child(Base):
    class Meta(Base.Meta):  # this
        pass

class GrandChild(Child):
    class Meta(Child.Meta):  # this
        pass

这个问题是在更改继承结构时很容易忽略标记为“this”的行。

这与Python2的超级要求父类名称的问题基本相同。

和我一样,我想要的是一种以不明确引用外部类库的方式编写这些行的方法。类似的东西:

class Base:
    class Meta:
        pass

class Child(Base):
    class Meta(super.Meta):  # this
        pass

class GrandChild(Child):
    class Meta(super.Meta):  # this
        pass

有没有这样做?

1 个答案:

答案 0 :(得分:0)

我认为您可以使用类工厂函数解决问题

def MetaClassFactory(name, SuperClass):
    newclass = type(name, (SuperClass.Meta,), {})
    return newclass


class Base(object):
    class Meta(object):
        someattr = 0

class Child(Base):
    Meta = MetaClassFactory("Meta", Base)

class GrandChild(Child):
    Meta = MetaClassFactory("Meta", Child)

# The class with its attribute is everywhere present (no AttributeError raised)
print "Base: {}, Child: {}, Grandchild: {}".format(Base.Meta.someattr, Child.Meta.someattr, GrandChild.Meta.someattr)

# Override it for Child (Grandchild inherits it)
Child.Meta.someattr = 1
print "Base: {}, Child: {}, Grandchild: {}".format(Base.Meta.someattr, Child.Meta.someattr, GrandChild.Meta.someattr)

两个印刷语句产生:

Base: 0, Child: 0, Grandchild: 0
Base: 0, Child: 1, Grandchild: 1