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

2024-10-01 15:43:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些类似于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

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


Tags: thedjango代码authenticationstyletastypiemetaclass
1条回答
网友
1楼 · 发布于 2024-10-01 15:43:38

在您的例子中,您似乎试图重写超类的meta属性。为什么不使用元继承呢?在

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

输出:

^{pr2}$

使TestResource的{}从父元继承(这里是authentication属性)。在

最后回答问题:

如果您真的想访问它(例如将内容附加到父列表等),可以使用您的示例:

class TestResource(SpecializedResource):
    class Meta(SpecializedResource.Meta):
        authentication = SpecializedResource.Meta.authentication # works (but hardcoding)

或者没有硬编码super类:

class TestResource(SpecializedResource):
    class Meta(SpecializedResource.Meta):
        authentication = TestResource.Meta.authentication # works (because of the inheritance)

相关问题 更多 >

    热门问题