首页 > 解决方案 > 使用对象调用函数?

问题描述

在两者之间编写一个布尔函数,它接受两个MyTime对象t1t2,作为参数,如果调用对象介于这两个时间之间,则返回 True 。假设t1 <= t2,并使测试在下限处关闭并在上限处打开,即如果 ,则返回 True t1 <= obj < t2

现在从这个问题的措辞来看,函数中似乎应该只有两个参数,但我看不到只使用两个参数来制作这样一个函数的方法。我的意思是我猜你可以创建另一个函数来创建一个作为MyTime对象的变量,但我只想将它保留在一个函数中而不是创建两个。问题的措辞使您看起来应该有Object(Function(t1,t2)),但我认为这是不可能的。是否可以仅使用两个参数来制作“介于”函数?这是我的代码

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))

标签: pythonpython-3.xobject

解决方案


您是 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参数是通过调用类实例的方法自动传入的。


推荐阅读