12

我有一些这样的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

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

4

1 回答 1

14

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

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

输出:

<__main__.MyCustomAuthentication object at 0x6160d10> 

这样TestResource'smeta是从父元继承的(这里是身份验证属性)。

最后回答问题:

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

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

或者没有对类进行硬编码:

class TestResource(SpecializedResource):
    class Meta(SpecializedResource.Meta):
        authentication = TestResource.Meta.authentication # works (because of the inheritance)
于 2013-10-14T15:36:02.163 回答