2015-04-06 85 views
0

我想要定義一個具有3個屬性的時間類:小時,分鐘和秒。以下是我迄今爲止:在定義的時間類中使用方法

class Time: 
    '''A class that stores information about time. Attributes: H (int) 
     M (int) S (int)''' 


    def __init__(self, hours=0, minutes=0, seconds=0): 
     '''hours represents time in hours, minutes represents time in 
      minutes, and seconds represents time in seconds''' 
     self.H = hours 
     self.M = minutes 
     self.S = seconds 


    def __str__(self): 
     '''Creates a string for appropriate display of time''' 
     return str(self.H) + ':' + str(self.M) + ':' + str(self.S) 


    def clean(self): 
     '''Adjust Time object so that the number of seconds and minutes 
      is between 0 and 59''' 
     if self.S < 60: 
      return 
     else: 
      self.M = int(self.S/60)+self.M 
      self.S = self.S%60 
     if self.M < 60: 
      return 
     else: 
      self.H = int(self.M/60)+ self.H 
      self.M = self.M%60    
     return self.__str__() 


    def to_seconds(self): 
     '''Converts Time instance into seconds and returns the resulting 
      integer.''' 
     minutes = self.H * 60 + self.M 
     seconds = minutes * 60 + self.S 
     return seconds 


    def to_hours(self): 
     '''Converts Time instance into hours and returns the resulting 
      floating point number.''' 
     seconds = self.S * .001 
     minutes = self.M * .01 
     hours = self.H + minutes + seconds 
     return float(hours) 


    def addSeconds(self,seconds): 
     '''Takes an integer and adds it to the amount of seconds in the 
      Time instance''' 
     sum_of_seconds = seconds + self.to_seconds 
     self.clean(sum_of_seconds) 
     return self.__str__() 


    def plus(self,hours=0,minutes=0,seconds=0): 
     '''Takes an extra time object as an arguement and returns a new 
      Time object y adding the two Time instances together''' 
     time2 = Time(hours,minutes,seconds) 
     total_seconds_time1 = self.to_seconds() 
     total_seconds_time2 = self.to_seconds() 
     total_seconds = total_seconds_time1 + total_seconds_time2 
     newtime = total_seconds.clean() 
     return newtime 

我有以下煩惱: - 我應該.zfill使用到STR格式化爲HH:MM:SS帶前導零 - 我我的.plus方法返回AttributeError:'int'對象沒有屬性'clean'

+0

如果您有3個問題,請提出3個不同的問題,每個問題只有您的代碼的相關部分。請永遠清除(你的第二個問題不清楚),並說出你所嘗試過的,你得到的結果以及你想要的結果。 –

回答

0

您對zfill有什麼問題?這很簡單:my_string.zfill(2),爲了得到至少有兩個字符的字符串,必要時填充前導零,以滿足雙字符要求。

你需要包括一些爲什麼你的乾淨的方法不工作的例子。不過,我會說,你的代碼不會做你認爲它的做法。 return聲明結束該過程。所以,如果你的秒數少於60,那麼程序結束,它從不檢查你的分鐘。

至於第三個問題,你的plus方法不起作用,因爲你試圖調用一個不存在的整數的clean方法。 total_seconds是加入total_seconds_time1total_seconds_time2的結果,兩者都是由to_seconds方法返回的整數。

+0

對於zfill問題,需要我的返回值如下所示:02:05: 22(而不是2:5:22) – Brett

+1

試試這個:'return str(self.H).zfill(2)+':'+ str(self.M).zfill(2)+':'+ str(self。 S).zfill(2)'。您將每個整數強制爲一個字符串,因此您可以爲每個整數調用該字符串的zfill方法。 – paidhima

相關問題