2013-11-25 155 views
1

我不知道爲什麼通過創建兩個不同的實例我得到相同的結果?我的邏輯有什麼問題? (更新工作)兩個不同的實例給出相同的結果(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] 

感謝支持,
亞歷

+0

你會得到什麼結果? –

+3

'len(date)<366)'看起來不正確。您可能必須在'makeDate()''date''中使用'全球日期' – karthikr

+0

2012年的兩個日期列表,而我預計2012年會有一個日期,2013年會有另一個。 – Alekz112

回答

4

makeDate方法修改全局date。當你第一次打電話給它時,它將2012年的所有366天添加到空列表中,然後給你第364天。當你第二次打電話給它時,它將在2013年的所有365天中增加366天的現有清單,然後給你第364天,這與以前一樣。

這正是您不想使用全局變量的原因。只需在__init__方法中輸入self.date = [],並使用self.date而不是date,並且每個實例都有自己的列表。

或者您可以將其設置爲局部變量而不是全局變量,因此makeDate只是在每次調用時創建並返回一個新列表。

+0

拍攝,現在我看到了邏輯。萬分感謝!但如何正確地改變它?我的意思是,如何正確地在__init__函數中放置self.date? – Alekz112

+0

@ user2619492:我在第二段中解釋過:「只需在'__init__'方法中放入'self.date = []'。」你不明白什麼? – abarnert

+0

雖然 – Alekz112

0

您正在追加到全局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 
1

全球date是由Date所有實例共享,所以當你從Date.makeDate返回date,您返回到列表的引用。 date2[364]返回的是與​​相同的元素。在致電Date.__getitem(date2, 364)後,您應該注意到date在列表中有700多個項目。雖然​​和date[364]將是相同的,date2[364]是真的像date[728]。您需要在每次調用makeDate或更好的時候重置date的值,然後排除全局變量並使用makeDate內的本地列表,每次初始化爲[]

0

變量date綁定到您在類Date以外創建的列表。

然後,在各種類別功能中,您可以操作變量date,它指的是外部實體列表。這會向列表中添加各種值(同樣,它不會與任何特定的類實例關聯),然後返回列表。

這就像做:

x = 3 
def f(incr): 
    global x 
    x += incr 
    return x 

,然後不知道爲什麼,增量(1)返回4之後,第二個增量(1)返回5.這是因爲你修改「全局變量」。

這不是完全清楚你來我想怎麼這一切工作,但很明顯,第一步就是要擺脫的date的「全局變量」的版本,並添加本地或實例變量的版本需要的地方。

相關問題