如何在Python中访问超类的元属性?

Sub*_* S. 9 python django

我有一些像Django-Tastypie这样的代码:

class SpecializedResource(ModelResource):
    class Meta:
        authentication = MyCustomAuthentication()

class TestResource(SpecializedResource):
    class Meta:
        # the following style works:
        authentication = SpecializedResource.authentication
        # but the following style does not:
        super(TestResource, meta).authentication
Run Code Online (Sandbox Code Playgroud)

我想知道在没有硬编码超类名称的情况下访问超类的元属性的正确方法是什么.

ast*_*eal 9

在您的示例中,您似乎正在尝试覆盖超类元的属性.为什么不使用元继承?

class MyCustomAuthentication(Authentication):
    pass

class SpecializedResource(ModelResource):
    class Meta:
        authentication = MyCustomAuthentication()

class TestResource(SpecializedResource):
    class Meta(SpecializedResource.Meta):
        # just inheriting from parent meta
        pass
    print Meta.authentication
Run Code Online (Sandbox Code Playgroud)

输出:

<__main__.MyCustomAuthentication object at 0x6160d10> 
Run Code Online (Sandbox Code Playgroud)

从而使TestResourcemeta是从父元(这里的认证属性)继承.

最后回答了这个问题:

如果你真的想要访问它(例如将东西附加到父列表等),你可以使用你的例子:

class TestResource(SpecializedResource):
    class Meta(SpecializedResource.Meta):
        authentication = SpecializedResource.Meta.authentication # works (but hardcoding)
Run Code Online (Sandbox Code Playgroud)

或者没有硬编码类:

class TestResource(SpecializedResource):
    class Meta(SpecializedResource.Meta):
        authentication = TestResource.Meta.authentication # works (because of the inheritance)
Run Code Online (Sandbox Code Playgroud)