我正在创建一个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
是我的自定义模块的名称。
答案 0 :(得分: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
,但这只会将问题隐藏起来直到以后。
Sidenote :根据我的评论,您应该查看style guide,特别是有关方法的命名约定...
答案 1 :(得分:0)
XDocument xdoc = new XDocument();
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
XElement line = new XElement("line");
XElement itemid = new XElement("field", dr.Cells["Item ID"].Value.ToString());
itemid.Add(new XAttribute("name", "item_id"));
line.Add(itemid);
XElement itemname = new XElement("field", dr.Cells["Item Name"].Value.ToString());
itemname.Add(new XAttribute("name", "item_name"));
line.Add(itemname);
XElement cost = new XElement("field", dr.Cells["Cost"].Value.ToString());
cost.Add(new XAttribute("name", "cost"));
line.Add(cost);
xdoc.Add(line);
break;
}
xdoc.Save(@"C:\xmltest\test3.xml");
仅在以下情况下初始化:
models_path
有一些文件/目录和self.project_dir
如果其中一个条件未满,则models
未初始化。