Write a Boolean function between that takes two
MyTime
objects,t1
andt2
, as arguments, and returns True if the invoking object falls between the two times. Assumet1 <= t2
, and make the test closed at the lower bound and open at the upper bound, i.e. return True ift1 <= obj < t2
.
现在从这个问题的措辞来看,函数中似乎应该只有两个参数,但我看不出只使用两个参数来创建这样一个函数的方法。我的意思是我想你可以创建另一个函数来创建一个变量,该变量是 MyTime
对象,但我只打算将它保留为一个功能而不是两个。问题的措辞让你看起来应该有 Object(Function(t1,t2))
但我不认为这是可能的。是否可以只使用两个参数来创建“between”函数?这是我的代码
class MyTime:
""" Create some time """
def __init__(self,hrs = 0,mins = 0,sec = 0):
"""Splits up whole time into only seconds"""
totalsecs = hrs*3600 + mins*60 + sec
self.hours = totalsecs // 3600
leftoversecs = totalsecs % 3600
self.minutes = leftoversecs // 60
self.seconds = leftoversecs % 60
def __str__(self):
return '{0}:{1}:
{2}'.format(self.hours,self.minutes,self.seconds)
def to_seconds(self):
# converts to only seconds
return (self.hours * 3600) + (self.minutes * 60) + self.seconds
def between(t1,t2,x):
t1seconds = t1.to_seconds()
t2seconds = t2.to_seconds()
xseconds = x.to_seconds()
if t1seconds <= xseconds < t2seconds:
return True
return False
currentTime = MyTime(0,0,0)
doneTime = MyTime(10,3,4)
x = MyTime(2,0,0)
print(between(currentTime,doneTime,x))
最佳答案
你是 100% 正确的,它确实需要三个参数。如果你把它写成 MyTime
类的成员函数,它会得到第三个参数,self
:
class MyTime():
# the guts of the class ...
def between(self, t1, t2):
t1seconds = t1.to_seconds()
t2seconds = t2.to_seconds()
myseconds = self.to_seconds()
return t1seconds <= myseconds < t2seconds
您可以将此方法用于:
currentTime = MyTime(0, 0, 0)
doneTime = MyTime(10, 3, 4)
x = MyTime(2, 0, 0)
x.between(currentTime, doneTime)
self
参数是通过调用类实例上的方法自动传入的。
关于python - 使用对象调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51353229/