我想要定義一個具有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'
如果您有3個問題,請提出3個不同的問題,每個問題只有您的代碼的相關部分。請永遠清除(你的第二個問題不清楚),並說出你所嘗試過的,你得到的結果以及你想要的結果。 –