将布尔函数变成方法? (蟒蛇)

问题描述 投票:0回答:1

我正在努力完成编程课的作业。它给出的问题是:

  1. 在其间编写一个布尔函数,以两个 MyTime 对象 t1 和 t2 作为参数,如果调用对象位于两个时间之间,则返回 True。假设 t1 <= t2, and make the test closed at the lower bound and open at the upper bound, i.e. return True if t1 <= obj < t2.
  2. 将上面的函数变成MyTime类中的方法。

我的代码如下所示:

class MyTime:
  
  def __init__ (self, hrs=0, mins=0, secs=0):
    t_secs = hrs*3600 + mins*60 + secs
    self.hrs = t_secs // 3600 # Split in h, m, s
    left_over_secs = t_secs % 3600
    self.mins = left_over_secs // 60
    self.secs = left_over_secs % 60

    #print (t_secs)

  def increment(t, secs):
    t.seconds += secs
    while t.seconds >= 60:
        t.seconds -= 60
        t.minutes += 1

    while t.minutes >= 60:
        t.minutes -= 60
        t.hours += 1

  def __str__(self):
    return "{0}:{1}:{2}".format(self.hrs,self.mins,self.secs)
  
  def __lt__(self,t2):
    if self.hrs<t2.hrs:
      return True
    if t2.hrs<self.hrs:
      return False
    if self.hrs==t2.hrs:
      if self.mins<t2.mins:
        return True
      if t2.mins<self.mins:
        return False
    if self.mins==t2.mins:
      if self.secs<t2.secs:
        return True
      if t2.secs<self.secs:
        return False

  def __eq__(self,t2):
    return bool(self.hrs == t2.hrs and self.mins == t2.mins and self.secs == t2.secs)
  
  def __le__(self,t2):
    return bool(self.hrs <= t2.hrs and self.mins <= t2.mins and self.secs <= t2.secs)

  def __ge__(self,t2):
    return bool(self.hrs >= t2.hrs and self.mins >= t2.mins and self.secs >= t2.secs)

  def __ne__(self,t2):
    return bool(self.hrs != t2.hrs or self.mins != t2.mins or self.secs != t2.secs)

  def __add__(self,t2):
    h=self.hrs+t2.hrs
    m=self.mins+t2.mins
    s=self.secs+t2.secs
    
    while s > 59:
      s-=60
      m+=1
    while m>59:
      m-=60
      h+=1

    sum_t=MyTime(h,m,s)
    return sum_t

  def between(self, t1, t2, t3):
    if t1.hours < t2.hours and t2.hours < t3.hours:
      return True
    else:
      return False

我的主要/运行代码如下所示:


from MyTime import MyTime

t1 = MyTime(1,3,30)
t2 = MyTime(1,4,16)
t3 = MyTime(3,4,26)

def between(self, t1, t2, t3):
    if t1.hours < t2.hours and t2.hours < t3.hours:
      return True
    else:
      return False


print(between(t1, t2, t3))
print(t2.between(t1, t3))

我不断收到“TypeError: Between() miss 1 requiredpositional argument: 't3'”错误,但我对如何修复它感到困惑?

我最初提交它时,在 MyTime 文件中注释掉了 Between 语句,并且以某种方式起作用了。我可能也改变了其他东西,但我已经把它弄乱了太久了,记不清了。请帮助我只有一次重新提交的机会,我被难住了!

python methods boolean
1个回答
0
投票

您的自由函数

def between
不应该有
self

-def between(self, t1, t2, t3):
+def between(t1, t2, t3):
    if t1.hours < t2.hours and t2.hours < t3.hours:
      return True
    else:
      return False

否则,当你调用

between(t1, t2, t3)
时,参数会以你意想不到的方式分配,就像你这样做一样:

print(between(self = t1, t1 = t2, t2 = t3, t3 = ... missing!)) 
© www.soinside.com 2019 - 2024. All rights reserved.