2016-09-07 30 views
0

如何在不導入其他模塊的情況下創建一個可以像這樣操作的類?增加兩個沒有模塊的類的屬性?

>>date(2014,2,2) + delta(month=3) 
>>(2014, 5, 2) 
>> 
>>date(2014, 2, 2) + delta(day=3) 
>>(2014, 2, 5) 
>>date(2014, 2, 2) + delta(year=1, month=2) 
>>(2015, 4, 2) 

這是我的代碼:

# class delta(date): 
#  year = date(year) 
#  def __init__(self,y,m,d): 
#   self.y = y + year 
#   self.m = m 
#   self.d = d 
#  def __call__(self): 
#   return self.y, self.m, self.d 
class date(object): 
    def __init__(self,year,month,day): 
     self.year = year 
     self.month = month 
     self.day = day 
    def __call__(self): 
     return self.year, self.month, self.day 
+1

'delta'必須是它自己的類,你能在'date'類中做一個'delta'函數嗎? – depperm

+0

我把delta作爲 –

+0

類,當然,有很多方法可以做到這一點。看看'__add__'和'__iadd__'。 –

回答

1

覆蓋的__add__方法。在delta類中給出默認參數__init__,這樣你就可以只用一個或兩個參數來調用它。

class delta(): 
    def __init__(self,year=0,month=0,day=0): 
     self.y = year 
     self.m = month 
     self.d = day 
    def __call__(self): 
     return self.y, self.m, self.d 

class date(): 
    def __init__(self,year,month,day): 
     self.year = year 
     self.month = month 
     self.day = day 
    def __call__(self): 
     return self.year, self.month, self.day 
    def isLeapYear (self): 
     if ((self.year % 4 == 0) and (self.year % 100 != 0)) or (self.year % 400 == 0): 
      return True 
     return False 
    def __add__(self,delta): 
     self.year=self.year+delta.y 
     self.month=self.month+delta.m 
     if self.month>12: 
      self.month=self.month%12 
      self.year+=1 
     self.day=self.day+delta.d 
     if self.isLeapYear() and self.day>29: 
      self.day=self.day%29 
      self.month+=1 
     elif not self.isLeapYear() and self.day>28: 
      self.day=self.day%28 
      self.month+=1 
     return self.year, self.month, self.day 

print(date(2014, 2, 2) + delta(year=1, month=2)) # (2015, 4, 2) 

birthdate=date(1990,1,1) 
currentyear=birthdate+delta(year=20,month=2,day=5) 
print(currentyear) # (2010, 3, 6) 
+0

哇..這是完美的答案...謝謝先生 –

相關問題