Python类没有按预期工作?

时间:2013-12-28 12:21:46

标签: class python-2.7

以下代码为Sunday.no_jobs提供了结果“0”,但周日有5个工作。

sunday = workbook.sheet_by_name('Sunday')

class Day:
    def __init__(self, day):
        self.day = day

    jobs = {}
    def getjobs(self, day): #populates a dictionary with the information from an excel sheet
       for i in range(start_row,day.nrows):
          self.jobs[i-1] = [str(day.cell_value(i,0)).upper(), str(day.cell_value(i,1)).upper(), str(day.cell_value(i,2)).upper(), str(day.cell_value(i,3)).upper(), str(xlrd.xldate_as_tuple(day.cell_value(i,4),0)[3])+":"+str(xlrd.xldate_as_tuple(day.cell_value(i,4),0)[4]), str(day.cell_value(i,5)).upper(), str(day.cell_value(i,6)).upper(), str(day.cell_value(i,7)).upper(), str(day.cell_value(i,8)).upper(), str(day.cell_value(i,9)).upper(), str(day.cell_value(i,10)).upper(), str(day.cell_value(i,11)).upper(), str(day.cell_value(i,12)).upper(), str(day.cell_value(i,13)).upper(), str(day.cell_value(i,14)).upper(), str(day.cell_value(i,15)).upper(), str(day.cell_value(i,16)).upper(), str(day.cell_value(i,17)).upper(), str(day.cell_value(i,18)).upper()]

    no_jobs = len(jobs)

Sunday = Day(sunday)

print Sunday.day

Sunday.getjobs(Sunday.day)

print Sunday.jobs[1][1]

print Sunday.no_jobs

如果我这样做,这是有效的:

print len(Sunday.jobs)

如何修改课程以便“打印Sunday.no_jobs”会产生“5”?

1 个答案:

答案 0 :(得分:0)

您需要使用Day关键字创建类self的变量属性:

class Day:
    def __init__(self, day):
        self.day = day
        self.jobs = {}
        self.no_jobs = 0
    def getjobs(self): 
        """populates a dictionary with the information from an excel sheet"""
        for i in range(start_row, self.day.nrows): # note self.day
            ... # use self.jobs here
        self.no_jobs = len(self.jobs)

或者,将no_jobs设为属性:

    @property
    def no_jobs(self):
        return len(self.jobs)