python-3.x 当运行代码使用类命名为时钟存储时间我得到不正确的输出,问题似乎是当分裂的时间了

iszxjhcz  于 2023-03-31  发布在  Python
关注(0)|答案(1)|浏览(73)

我正在写一个类Clock来存储时间。关于Clock类,你应该知道一些事情。Clock类应该有三个变量,分别表示小时、分钟和秒。确保分钟和秒总是在0-59之间(包括两者),小时在0-23之间(包括两者)。
我的代码似乎不能正常工作,因为当我运行它时,它给了我错误的输出。#main不能更改,我只能更改类Clock。
预期输出为:

Testing initialization:   
a = 00:00:00  
b = 12:23:53   
c = 18:03:21   
Testing set functions:    
d = 15:37:38   
Testing addition, subtraction and multiplication
e = b + c = 06:27:14
f = e - b = 18:03:21
g = b * 0.8 = 09:55:06
h = d * 2 = 07:15:16
Test get functions
e = 06:27:14
e.hours() = 6
e.minutes() = 27
e.seconds() = 14
Testing comparisons:
06:27:13 < 06:27:14
12:23:53 > 10:18:42
18:03:21 == 18:03:21
18:03:21 >= 18:03:21
12:23:53 <= 18:03:21

我的输出:

Testing initialization:
a = 00:00:00
b = 12:23:53
c = 18:03:21

Testing set functions:
d = 00:00:00

Testing addition, subtraction and multiplication
e = b + c = 06:27:14
f = e - b = 18:03:21
g = b * 0.8 = 09:55:06
h = d * 2 = 00:00:00

Test get functions
e = 06:27:14
e.hours() = 6
e.minutes() = 27
e.seconds() = 14

Testing comparisons:
06:27:13 < 06:27:14
12:23:53 > 09:55:06
18:03:21 == 18:03:21
18:03:21 >= 18:03:21
12:23:53 <= 18:03:21

我的当前代码:

class Clock:
    """
    This class defines a Clock object with the hours, minutes, and seconds attributes, and includes methods for setting the time, 
    converting to seconds, creating a new Clock object from seconds, and performing arithmetic operations with other Clock objects.
    """
    def __init__(self, hours=0, minutes=0, seconds=0):
        """
        Initializes a Clock object with the given hours,
        minutes, and seconds. If hours is passed as a string in the format "HH:MM:SS", 
        it will be split and converted to integers.
        """
        if isinstance(hours, str):
            hours, minutes, seconds = map(int, hours.split(':'))
        self.__hours = hours
        self.__minutes = minutes
        self.__seconds = seconds
    
    def __str__(self):
        """
        Returns a string representation of the Clock object in the format "HH:MM:SS".
        """
        return "{:02d}:{:02d}:{:02d}".format(self.__hours, self.__minutes, self.__seconds)

    def set_hours(self, hours):
        """
        Sets the hours attribute of the Clock object to the given value, if it is between 0 and 23.
        """
        if 0 <= hours <= 23:
            self.__hours = hours

    def set_minutes(self, minutes):
        """
        Sets the minutes attribute of the Clock object to the given value, if it is between 0 and 59.
        """
        if 0 <= minutes <= 59:
            self.__minutes = minutes

    def set_seconds(self, seconds):
        """
        Sets the seconds attribute of the Clock object to the given value, if it is between 0 and 59.
        """
        if 0 <= seconds <= 59:
            self.__seconds = seconds

    def hours(self):
        """
        Returns the value of the hours attribute of the Clock object.
        """
        return self.__hours

    def minutes(self):
        """
        Returns the value of the minutes attribute of the Clock object.
        """
        return self.__minutes

    def seconds(self):
        """
        Returns the value of the seconds attribute of the Clock object.
        """
        return self.__seconds

    def __add__(self, other):
        """Adds the total seconds of the current Clock object and the other Clock 
        object and returns a new Clock object with the sum, wrapping around to 0:00:00 if the total exceeds 24 hours."""
        total_seconds = self.__to_seconds() + other.__to_seconds()
        return Clock.from_seconds(total_seconds % (24 * 3600))

    def __sub__(self, other):
        total_seconds = self.__to_seconds() - other.__to_seconds()
        '''return Clock.from_seconds(total_seconds)'''
        return Clock.from_seconds(total_seconds % (24 * 3600))

    '''def __mul__(self, factor):
        total_seconds = round(self.__to_seconds() * factor)
        return Clock.from_seconds(total_seconds)'''
    def __mul__(self, factor):
        """
         Multiplies the total seconds of the current Clock object by the given factor and returns a new Clock object with the product, 
         wrapping around to 0:00:00 if the total exceeds 24 hours.
        """
        total_seconds = round(self.__to_seconds() * factor)
        while total_seconds >= 24 * 3600:
            total_seconds -= 24 * 3600
        return Clock.from_seconds(total_seconds)

    def __to_seconds(self):
        """
        Converts the time of the Clock object to the total number of seconds and returns the result.
        """
        return self.__hours * 3600 + self.__minutes * 60 + self.__seconds

    @staticmethod
    def from_seconds(total_seconds):
        """
        Creates a new Clock object from the given total number of seconds and returns the result.
        """
        hours = total_seconds // 3600
        minutes = (total_seconds % 3600) // 60
        seconds = total_seconds % 60
        return Clock(hours, minutes, seconds)

    def __lt__(self, other):
        """
        Compares the total seconds of the current Clock object and the other Clock object and returns True 
        if the current Clock object is less than the other Clock object.
        """
        return self.__to_seconds() < other.__to_seconds()

    def __gt__(self, other):
        """
        Compares the total seconds of the current Clock object and the other Clock object and returns True if the current Clock object is greater than the other Clock object.
        """
        return self.__to_seconds() > other.__to_seconds()

    def __eq__(self, other):
        """
        Compares the total seconds of the current Clock object and the other Clock object and returns True if they are equal.
        """
        return self.__to_seconds() == other.__to_seconds()

    def __ge__(self, other):
        """
        Compares the total seconds of the current Clock object and the other Clock object and returns True if the current Clock object is greater than or equal to the other Clock object.
        """
        return self.__to_seconds() >= other.__to_seconds()

    def __le__(self, other):
        """
        Compares the total seconds of the current Clock object and the other Clock object and returns True if the current Clock object is less than or equal to the other Clock object.
        """
        return self.__to_seconds() <= other.__to_seconds()



#main
print('Testing initialization:')
a = Clock()
b = Clock('12:23:53')
c = Clock(18,3,21)
print('a =', a)
print('b =', b)
print('c =', c)
print()
print('Testing set functions:')
d = Clock()
d.set_hours(37)
d.set_minutes(142)
d.set_seconds(938)
print('d =', d)
print()
print('Testing addition, subtraction and multiplication')
e = b + c
print('e = b + c =', e)
f = e - b
print('f = e - b =', f)
g = b * 0.8
h = d * 2
print('g = b * 0.8 =', g)
print('h = d * 2 =', h)
print()
print('Test get functions')
print('e =', e)
print('e.hours() =', e.hours())
print('e.minutes() =', e.minutes())
print('e.seconds() =', e.seconds())
print()
print('Testing comparisons:')
i = Clock(6,27,13)
if i < e:
    print(i,'<',e)
if b > g:
    print(b,'>',g)
if c == f:
    print(c, '==', f)
if c >= c:
    print(c, '>=', c)
if b <= c:
    print(b, '<=', c)
omhiaaxx

omhiaaxx1#

根据预期产出(d 示例的),你的setter不正确。你似乎只考虑了时间戳内的有效值,但例如3723 秒的值也是有效的**(表示1 小时 2 分钟 3),并且这些值必须与现有值组合(相加)(除了必须重写的最小值)。
因此,您的setters是错误的。
下面是修复方法(仅列出修改后的方法):

# ...

    def set_hours(self, hours):
        self.__hours = hours % 24

    def set_minutes(self, minutes):
        h, m = divmod(minutes, 60)
        self.__minutes = m
        self.set_hours(self.hours() + h)

    def set_seconds(self, seconds):
        hm, s = divmod(seconds, 60)
        h, m = divmod(hm, 60)
        self.__seconds = s
        self.set_minutes(self.minutes() + m)
        self.set_hours(self.hours() + h)

# ...

也许这只是一个(相当入门级的)练习,但值得一提的是[Python.Docs]:time -时间访问和转换,专门用于处理时间对象。

相关问题