2016-12-02 80 views
1

試圖在自己內部引用一個類。對於例如Python:如何在自己內部引用一個類?

class Test: 
    FOO_DICT = {1 : Test.bar} # NameError: name 'Test' is not defined 

    @staticmethod 
    def bar(): 
     pass 

這種用法是否有意義?任何更好的選擇? 謝謝!

+0

只要使用'欄'本身。 – DyZ

+0

@DYZ那不行,因爲'bar'還沒有被定義。 –

+0

正如有人在下面建議的那樣,改變定義的順序。 – DyZ

回答

3

如果你想在字典中的類:首先定義功能,並刪除測試:

class Test: 
    @staticmethod 
    def bar(): 
     pass 

    FOO_DICT = {1: bar} 
+0

可能應該避免順序依賴,但似乎沒有更好的模式。 – cheng

0

您可以移動FOO_DICT = {1 : Test.bar}課外的是這樣的:

class Test: 
    @staticmethod 
    def bar(): 
     pass 
Test.FOO_DICT = {1: Test.bar} 
+1

這違反了類封裝,應該避免。 – DyZ

相關問題