使用对象调用函数?

Mat*_*att 2 python object python-3.x

在两个MyTime对象之间写一个布尔函数,t1t2作为参数,如果调用对象落在两次之间,则返回True.假设t1 <= t2,并使测试在下限处关闭并在上限处打开,即返回True,如果t1 <= 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))
Run Code Online (Sandbox Code Playgroud)

ill*_*der 5

你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
Run Code Online (Sandbox Code Playgroud)

您可以使用此方法:

currentTime = MyTime(0, 0, 0)
doneTime = MyTime(10, 3, 4)
x = MyTime(2, 0, 0)
x.between(currentTime, doneTime)
Run Code Online (Sandbox Code Playgroud)

self参数在自动通过调用类的一个实例的方法传递.