两个不同的实例给出相同的结果(Python)

2024-04-19 20:47:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道为什么创建两个不同的实例会得到相同的结果?我的逻辑怎么了?(更新为工作)

基本上,这个类应该创建相应年份的日期列表

代码本身:

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]

感谢您的支持,
亚历克斯


Tags: orselfdatereturnifdefyearday
3条回答

您的makeDate方法修改全局date。当你第一次调用它时,它会将2012年的366天全部添加到空列表中,然后给出第364天。第二次调用时,在第二个实例中,它会将2013年的所有365天添加到现有的366天列表中,然后给出第364天,与以前相同。你知道吗

这正是你不想使用globals的原因。只要在__init__方法中放置一个self.date = [],并使用self.date而不是date,每个实例都有自己的列表。你知道吗

或者你可以把它变成一个局部变量而不是一个全局变量,这样makeDate就可以在每次调用它时创建并返回一个新的列表。你知道吗

全局dateDate的所有实例共享,因此当您从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应该是什么?我猜你的意思可能是它是一个局部变量

def makeDate(self):
    date = []           # brand new empty list
    month = 1
    while month <= 12:
        day = 1
        while day <= self.daysInMonth(month):
            if (self.year%4 == 0 and len(date) < 366) or (self.year%4 != 0 and len(date) < 365):
                date.append(str(self.dateStr(day)) + u'.' + str(self.dateStr(month)) + u'.' + str(self.year))
            day += 1
        month += 1
    return date

相关问题 更多 >