我创建了一个名为“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)
我创建了另一个应该导入该模块的文件(保存为timeADT.py)并测试每个操作。但是,我无法弄清楚如何正确调用每个函数。我想把时间设置为(小时,分钟,秒),但是当我调用timeADT.hour(5,12,49)时,它会给我一个错误,并说我应该只有一个参数。
import timeADT
timeADT.hour(5,49,13)
我是python的新手,对于我从这里离开的地方非常困惑。任何有关如何创建此“测试”文件的帮助将非常感激!
谢谢。
答案 0 :(得分:2)
您应首先构造对象,然后再使用它。 试试这个:
from timeADT import Time
time = Time(5,49,13)
print time.hour, time.min, time.sec
答案 1 :(得分:0)
但也存在其他问题:
def numSec(selfotherTime):
self
def advanceBy(numSeconds):
此处self,
完全缺失。