2013-10-14 66 views
9

我有一些像這樣的代碼Django-Tastypie如何在Python中訪問超類的元屬性?

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 

我想知道什麼是訪問超類的元屬性沒有硬編碼的超類的名稱正確的方法。

+0

在提供超類名稱的片段中沒有硬編碼 - 'super()'採用* current *類的名稱。 –

+0

正如評論所說,它不起作用:P –

回答

8

在你的例子中,你似乎試圖重寫超類的元屬性。爲什麼不使用元繼承?

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) 

或者沒有硬編碼類:

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

這正是我在不知情的情況下正在尋找的東西。謝謝!實際上,不需要在TestResource中聲明身份驗證。當元繼承起作用時,它很簡單。 –

+0

你能確認這是否適用於Python 3.4? – Akhorus