我正在創建一個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
是我的自定義模塊的名稱。
你能給完整的追溯?另外'__ weird_method_names__'有什麼 - 這些不是真正的魔術方法,你不應該這樣命名它們。 – jonrsharpe
分離將用於創建其他類的屬性的方法。這是不是約定還是我錯過了什麼?是的,當然。 – CiaranWelsh
如果它們對於該類是私有的,則使用'_single_leading_underscore'。 '__double_leading_and_trailing_underscore__'用於預定義的「魔術方法」*,比如'__init__'和'__str__'。 – jonrsharpe