python - 如何在 Python 中访问父类(super class)的元属性?

标签 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

我想知道在不对父类(super class)名称进行硬编码的情况下访问父类(super class)元属性的正确方法是什么。

最佳答案

在您的示例中,您似乎试图覆盖父类(super class)的元属性。为什么不使用元继承?

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> 

因此 TestResourcemeta 是从父元(这里是身份验证属性)继承的。

终于回答问题了:

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

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)

关于python - 如何在 Python 中访问父类(super class)的元属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19362501/

相关文章:

python - 有没有办法发送 "refresh"请求?

python -/n 漂亮的汤文

python - 当使用 Selenium 和 Python 传递值时,动态下拉列表不会填充 https ://www. nseindia.com/上的自动建议

python - 检查用户是否在 Django 模板中订阅了 dj-stripe

python - 如何在 django Rest 中自动继承外键模型的字段?

python - Django 查看返回带有额外信息的查询集

python - 对不是模型的对象使用 Django JSON 序列化程序

python - 将excel读入pandas dataframe时如何区分两行不同颜色?

python - 为什么我的 python 脚本会随机被杀死?

python - 根据翻译区分列表