简体   繁体   English

在python中的循环中创建类的实例?

[英]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: 所以我试图使用OOP在python中创建日历,在这里我设置了Month类:

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: 效果很好,这是Year类的:

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: 问题是,月份总是从我在for循环之前提供的“星期六”开始,尽管变量FD(第一天)在每次迭代中都重新分配给了m.NMFD,这是输出:

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. 我尝试使用字典或元组代替嵌套列表,但是它没有用,并且在Stack Overflow上也找不到令人满意的答案……任何帮助将不胜感激,在此先感谢您。

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. 每当您构造类时,都会调用该类变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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