所以我创建了一个班级......
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)
现在我想使用我收集的变量来迭代excel文件,使用上面详述的类为每一行创建对象。
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的对象,但它改变了变量。
是否可以在循环中使用变量创建一堆对象?
答案 0 :(得分:2)
您应该使用python词典(tutorial page describing dictionaries),而不是使用eval
函数创建一堆变量:
Dept["gds_"+str(deptno)] = Dept_member(q_budget, os_budget, deptname)
之后,您可以使用以下字符从字典中获取对象:
Dept['gds_180024446']
答案 1 :(得分:0)
我认为您需要使用像
这样的eval函数eval("gds_" + str(deptno) + " = Dept_member(q_budget, os_budget, deptname)")