简体   繁体   中英

Creating instances of a class in a loop in python?

So I'm trying to make a calendar in python using OOP, here I've set a Month class:

week_days=['Sat', 'Sun', 'Mon', 'Teu', 'Wed', 'Thu', 'Fri']

class Month(object):
    #class variable.
    days=[]

    def __init__(self, label, numdays, starts_with):
        self.label=label
        count=week_days.index(starts_with)
        for i in range(1, numdays+1):
            self.days.append([i, week_days[count]])
            count+=1
            if count>6:
                count=0                    #loop around week_days
        self.NMFD = week_days[count]       #next month 1st day

It works just fine, and here's the Year class:

months_list=[('Jan', 31), ('Feb', 29), ('Mar', 31), ('Apr', 30)...]

class Year(object):
    #class variable.
    months=[]

    def __init__(self):
        FD= 'Sat'
        for item in months_list:
            m=Month(item[0], item[1], FD)
            self.months.append(m)
            FD = m.NMFD

            #Debug...
            print m.label
            print m.days
            print 'Next month first day =' + FD
            print '\n'


if __name__ == '__main__':            
    year = Year()

The problem is that the months always start at the day 'Sat' that I provided before the for loop, although the variable FD (First Day) is reassigned in each iteration to m.NMFD, here's the output:

Jan
[[1, 'Sat'], [2, 'Sun'], [3, 'Mon'], [4, 'Teu']...[30, 'Sun'], [31, 'Mon']]
Next month first day =Teu

Feb
[[1, 'Sat'], [2, 'Sun'], [3, 'Mon'], [4, 'Teu']...[28, 'Mon'], [29, 'Teu']]
Next month first day =Wed

Mar
[[1, 'Sat'], [2, 'Sun'], [3, 'Mon'], [4, 'Teu']...[30, 'Thu'], [31, 'Fri']]
Next month first day =Sat

Apr
[[1, 'Sat'], [2, 'Sun'], [3, 'Mon'], [4, 'Teu']...[28, 'Fri'], [29, 'Sat'], [30, 'Sun']]
Next month first day =Mon

May
[[1, 'Sat'], [2, 'Sun'], [3, 'Mon'], [4, 'Teu']...]     #.....etc

I've tried using dictionaries or tuples instead of nested lists but it didn't work, and I didn't find satisfying answers here on Stack Overflow... any help would be much appreciated, thanks in advance.

Try this:

class Month(object):

    def __init__(self, label, numdays, starts_with):
        self.label=label
        self.days = []
        count=week_days.index(starts_with)
        for i in range(1, numdays+1):
            self.days.append([i, week_days[count]])
            count+=1
            if count>6:
                count=0                    #loop around week_days
        self.NMFD = week_days[count] 

The class variable is called everytime you construct the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM