所以我尝试使用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
它运作得很好,这里是年级:
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()
问题是这几个月总是从周六开始。我在for循环之前提供的,虽然变量FD(First Day)在每次迭代中被重新分配给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
我尝试过使用词典或元组而不是嵌套列表,但它没有用,而且我在Stack Overflow上找不到令人满意的答案...任何帮助都会非常感激,提前谢谢。
答案 0 :(得分:0)
试试这个:
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]
每次构造类时都会调用类变量。