在定义的时间类中使用方法

时间:2015-04-06 14:47:40

标签: python class methods

我正在尝试定义一个Time类,它有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并带有前导零 - 我不能在构造函数中使用我的.clean()方法 - 我的.plus方法返回AttributeError:'int'对象没有属性'clean'

1 个答案:

答案 0 :(得分:0)

你对zfill有什么问题?这很简单:my_string.zfill(2),获取一个至少包含两个字符的字符串,如果需要填充前导零以满足这两个字符的要求。

您需要提供一些清洁方法无效的示例。不过,我会说,你的代码并没有按照你的想法行事。 return语句结束了该过程。因此,如果你的秒数小于60,则程序结束,它永远不会检查你的分钟。

至于第三个问题,你的加法方法是不行的,因为你试图调用一个不存在的整数方法。 total_seconds是添加total_seconds_time1total_seconds_time2的结果,两者都是to_seconds方法返回的整数。