Skip to main content
 首页 » 编程设计

python之需要通过遍历 excel 文件来创建许多 python 对象

2024年11月01日9cyq1162

所以我创建了一个类...

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) 

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

>>>  
>>> 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 的对象,但它却改变了变量。

是否可以在循环中使用变量创建一堆对象?

请您参考如下方法:

你应该使用 python 字典(tutorial page describing dictionaries),而不是使用 eval 函数创建一堆变量:

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

之后,您可以使用以下命令从字典中获取您的对象:

Dept['gds_180024446']