2015-11-05 58 views
0

我正在創建一個Python類,但它似乎我無法讓構造函數類正常工作。這裏是我的課:UnboundLocalError初始化python類

class IQM_Prep(SBconcat): 
    def __init__(self,project_dir): 
     self.project_dir=project_dir #path to parent project dir 
     self.models_path=self.__get_models_path__() #path to parent models dir 
     self.experiments_path=self.__get_experiments_path__()  #path to parent experiemnts dir 

    def __get_models_path__(self): 
     for i in os.listdir(self.project_dir): 
      if i=='models': 
       models_path=os.path.join(self.project_dir,i) 
     return models_path 

    def __get_experiments_path__(self): 
     for i in os.listdir(self.project_dir): 
      if i == 'experiments': 
       experiments_path= os.path.join(self.project_dir,i) 
     return experiments 

當我初始化這個類:

project_dir='D:\\MPhil\\Model_Building\\Models\\TGFB\\Vilar2006\\SBML_sh_ver\\vilar2006_SBSH_test7\\Python_project' 

IQM= Modelling_Tools.IQM_Prep(project_dir) 

我得到以下錯誤:

Traceback (most recent call last): 

    File "<ipython-input-49-7c46385755ce>", line 1, in <module> 
    runfile('D:/MPhil/Python/My_Python_Modules/Modelling_Tools/Modelling_Tools.py', wdir='D:/MPhil/Python/My_Python_Modules/Modelling_Tools') 

    File "C:\Anaconda1\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 585, in runfile 
    execfile(filename, namespace) 

    File "D:/MPhil/Python/My_Python_Modules/Modelling_Tools/Modelling_Tools.py", line 1655, in <module> 
    import test 

    File "test.py", line 19, in <module> 
    print parameter_file 

    File "Modelling_Tools.py", line 1536, in __init__ 
    self.models_path=self.__get_models_path__() #path to parent models dir 

    File "Modelling_Tools.py", line 1543, in __get_models_path__ 
    return models_path 

UnboundLocalError: local variable 'models_path' referenced before assignment 

Modelling_Tools是我的自定義模塊的名稱。

+1

你能給完整的追溯?另外'__ weird_method_names__'有什麼 - 這些不是真正的魔術方法,你不應該這樣命名它們。 – jonrsharpe

+0

分離將用於創建其他類的屬性的方法。這是不是約定還是我錯過了什麼?是的,當然。 – CiaranWelsh

+2

如果它們對於該類是私有的,則使用'_single_leading_underscore'。 '__double_leading_and_trailing_underscore__'用於預定義的「魔術方法」*,比如'__init__'和'__str__'。 – jonrsharpe

回答

1

基於回溯,似乎之一:

def __get_models_path__(self): 
    for i in os.listdir(self.project_dir): # 1. this never loops; or 
     if i=='models': # 2. this never evaluates True 
      models_path=os.path.join(self.project_dir,i) # hence this never happens 
    return models_path # and this causes an error 

你應該檢討的os.listdir(self.project_dir)結果,找出原因;該目錄是空的或者其中沒有任何內容被命名爲models。您可以初始化該方法的開始處爲models_path = None,但這隻會在稍後纔會隱藏問題。


旁註:按我的意見,你應該看看style guide,特別是在命名約定的方法...

+0

是的,它是2.我之後的文件夾被稱爲「模型」而不是「模型」。謝謝 – CiaranWelsh

+1

@ user3059024如果'models' **或**' Models'都可以,因爲並非所有文件系統都區分大小寫,您可以考慮'if i.lower()=='models':'。 – jonrsharpe

0

models_path被初始化,只有當:

  • self.project_dir有一些文件/目錄和
  • 其中一個此文件/目錄有名稱models

如果其中一個條件未滿,則models_path未初始化。