测试抽象数据类型

2024-09-30 16:26:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个名为“Time”的ADT,需要创建一个新的python文件来测试它。以下是我所拥有的:

下面的代码使用datetime模块的时间功能实现Time ADT。在

import datetime

class Time :
     # Creates an new time instance and initializes it with the given time.
    def __init__ (self, hours, minutes, seconds):
        self.hr = hours
        self.min = minutes
        self.sec = seconds

    def hour(self):
        # Returns the hour as an integer between 0 to 23.
        return int(self.hr)

    def min(self):
        # Returns the minute as an integer between 0 to 59.
        return int(self.min)

    def sec(self):
        # Returns the seconds as an integer between 0 to 59.
        return int(self.sec)

    def numSec(self, otherTime):
        # Returns the number of seconds elapsed between this time and the otherTime.
        return abs(self.sec - otherTime.seconds)

    def advanceBy(self, numSeconds):
        # Advances the time by the given number of seconds.
        if (numSeconds + self.sec) < 60:
             seconds = seconds + numSeconds
        if ((numSeconds / 60) + self.min) < 60:
                minutes = minutes + int(numSeconds / 60)
                seconds = seconds + numSeconds % 60
        else:
                hours = hours + int(numSeconds / 3600)
                minutes = minutes + (numSeconds % 3600)
                seconds = seconds + numSeconds % 60

    def isPM(self):
        # Returns a Boolean indicating if this time is at or after 12 o'clock noon.
        if self.hr > 11:
            return True
        else:
            return False

    def comparable(self, otherTime):
        # Compares this time to the otherTime to determine their logical ordering.
        if datetime.time(otherTime) > datetime.time(self.hr, self.min, self.sec):
            return otherTime + "is after" + (self.hr, self.min, self.sec)
        else:
            return otherTime + "is before"+ (self.hr, self.min, self.sec)

    def toString(self):
        # Returns "HH:MM:SS XX", in the 12-hr format where XX is either AM/PM.
        if self.hr > 11:
            return "%d:%d%d PM" % (hours, minutes, seconds)
        else:
            return "%d:%d%d AM" % (hours, minutes, seconds)

我创建了另一个应该导入此模块的文件(另存为时间平均值)测试每一个操作。但是,我不知道如何正确地调用每个函数。我想把时间设为(小时,分钟,秒),但是当我打电话的时候时间ADT.hour(5,12,49)例如,它给了我一个错误,并说我应该只有一个参数。在

^{pr2}$

我是python的新手,我很困惑我将从这里走向何方。任何帮助如何创建这个“测试”文件将不胜感激!在

谢谢。在


Tags: theselfreturniftimedefhrsec
2条回答

但也存在其他问题:

def numSec(selfotherTime):

这是self后缺少的逗号

^{pr2}$

这里self,完全丢失。在

你应该先构造对象然后再使用它。 试试这个:

from timeADT import Time
time = Time(5,49,13)
print time.hour, time.min, time.sec

相关问题 更多 >