我不知道为什么创建两个不同的实例会得到相同的结果?我的逻辑怎么了?(更新为工作)
基本上,这个类应该创建相应年份的日期列表
代码本身:
class Date:
def __init__(self, year):
self.year = year
def dateStr(self, date):
if date < 10:
date = '0' + str(date)
else:
date = str(date)
return date
def daysInMonth(self, month):
if month == 4 or month == 6 or month == 9 or month == 11:
endDate = 30
if month == 1 or month == 3 or month ==5 or month == 7 or month ==8 or month == 10 or month == 12:
endDate = 31
if self.year%4 == 0 and month == 2:
endDate = 29
if self.year%4 != 0 and month == 2:
endDate = 28
return endDate
def makeDate(self):
self.date = []
month = 1
while month <= 12:
day = 1
while day <= self.daysInMonth(month):
self.date.append(str(self.dateStr(day)) + u'.' + str(self.dateStr(month)) + u'.' + str(self.year))
day += 1
month += 1
return self.date
def __str__(self):
return str(self.makeDate())
def __len__(self):
return len(self.makeDate())
def __getitem__(self, key):
return self.makeDate()[key]
date1 = Date(2012)
date2 = Date(2013)
print date1[364]
print date2[364]
感谢您的支持,
亚历克斯
您的
makeDate
方法修改全局date
。当你第一次调用它时,它会将2012年的366天全部添加到空列表中,然后给出第364天。第二次调用时,在第二个实例中,它会将2013年的所有365天添加到现有的366天列表中,然后给出第364天,与以前相同。你知道吗这正是你不想使用globals的原因。只要在
__init__
方法中放置一个self.date = []
,并使用self.date
而不是date
,每个实例都有自己的列表。你知道吗或者你可以把它变成一个局部变量而不是一个全局变量,这样
makeDate
就可以在每次调用它时创建并返回一个新的列表。你知道吗全局
date
由Date
的所有实例共享,因此当您从Date.makeDate
返回date
时,您将返回对该列表的引用。date2[364]
返回的元素与date1[364]
返回的元素相同。在调用Date.__getitem(date2, 364)
之后,您应该注意到date
在列表中有700多个条目。虽然date1[364]
和date[364]
是一样的,但date2[364]
实际上类似于date[728]
。您需要在每次调用makeDate
时重置date
的值,或者(更好的是)放弃全局变量并在makeDate
内使用一个局部列表,每次初始化为[]
。你知道吗您正在附加到全局
date
变量。因为它已经被第一个调用修改了,所以第二个调用什么也不做,只是返回它。你知道吗date
应该是什么?我猜你的意思可能是它是一个局部变量相关问题 更多 >
编程相关推荐