需要通过迭代excel文件来创build许多python对象

所以我创build了一个类…

class Dept_member: quarterly_budget = 0 outside_services = 0 regular_count = 0 contractor_count = 0 gds_function = '' dept_name = '' def __init__(self, quarterly_budget, outside_services, dept_name): self.quarterly_budget = quarterly_budget self.outside_services = outside_services self.dept_name = dept_name def regular_cost(self): print "%s" % str((self.quarterly_budget - self.outside_services) / self.regular_count) def contractor_cost(self): print "%s" % str(self.outside_services / self.contractor_count) 

现在我想使用我收集的variables,同时遍历一个excel文件,使用上面详述的类为每一行创build对象。

 for row in range(6,d_sh.get_highest_row()): if f_sh.cell(row=row, column=2).value: deptno = f_sh.cell(row=row, column=2).value q_budget = f_sh.cell(row=row, column=17).value #Q3 Actual os_budget = f_sh.cell(row=row, column=14).value deptnode = f_sh.cell(row=row, column=1).value chop = deptnode.split(" ") deptname = " ".join(chop[1:]) Dept = "gds_"+str(deptno) ### This is what I want my new object to be called! Dept = Dept_member(q_budget, os_budget, deptname) 

下面是运行后的一个空闲交互式会话的一些输出。

 >>> >>> deptno u'180024446' >>> q_budget 59412.00978792818 >>> os_budget 9973.898858075034 >>> deptnode u'M180024446 GDS Common HW FEP China' >>> deptname u'GDS Common HW FEP China' >>> Dept <__main__.Dept_member instance at 0x126c32050> >>> Dept.quarterly_budget 59412.00978792818 

我真正想要的是一个名为gds_180024446的对象,但是它改变了variables。

是否有可能使用循环中的variables创build一堆对象?

您应该使用Python字典( 教程页面描述字典 ),而不是使用eval函数创build一堆variables:

 Dept["gds_"+str(deptno)] = Dept_member(q_budget, os_budget, deptname) 

之后,你可以从字典中获取你的对象:

 Dept['gds_180024446'] 

我认为你需要使用eval函数

 eval("gds_" + str(deptno) + " = Dept_member(q_budget, os_budget, deptname)")