我有一些这样的代码 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>
因此 TestResource
的 meta
是从父元(这里是身份验证属性)继承的。
终于回答问题了:
如果您真的想访问它(例如将内容附加到父列表等),您可以使用您的示例:
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/